M
M
mitaichik2019-04-29 01:12:56
Java
mitaichik, 2019-04-29 01:12:56

Rx: how to repeat a subscription until a certain result?

Hello!
I can’t formulate the question exactly, I’ll describe what is needed:
Yes Single<SomeObject>- a request through Retrofit.
I SomeObjecthave a field status
And I need to repeat this request until this field takes a certain value.
And only after that subscribeshould get the result.
Something like repeatWhen, but in repeatWhen I cannot get the returned SomeObject to check the status (as I understand it from the documentation).
Is there a way to do this elegantly, purely on Rx?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
tuwkan, 2019-04-29
@tuwkan

In map, check the value and if not, throw an error. Next retryWhen

M
Maxim Moseychuk, 2019-04-29
@fshp

You can use switchMap recursively.
If the result is satisfactory, then return it wrapped in just. Otherwise, return a new Single by pulling the same function.
Consider a delay.

A
Alexander, 2019-10-02
@AlexKaram

Of course, I'm not an Rx master, but I came across this article on Habré Understanding retryWhen and repeatWhen
A piece of code from the article that applies to your problem

public void load() {
    Observable.combineLatest(
            repository.getSomething()
                    .retryWhen(retryHandler ->
                                       retryHandler.flatMap(
                                               err -> retrySubject.asObservable())),
            localStorage.fetchSomethingReallyHuge()
                    .retryWhen(retryHandler ->
                                       retryHandler.flatMap(
                                               nothing -> retrySubject.asObservable())),
            (something, hugeObject) -> new Stuff(something, hugeObject))
            .subscribe(stuff -> {}, err -> {});
}

The beauty of this approach is that the lambda passed to the operator retryWhen() is executed only after an error inside the source, respectively, if only one of the sources “errors”, then the resubscription will occur only to it, and the remaining chain below will wait for reexecution.
And if an error occurs inside both sources, then the same one retryHandlerwill work in two places.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question