Q:

Polling for long task for status update

I have a usecase where i need to the following

Call a POST endpoint which starts a process and gives a status
called "processing". Lets assume that we have  POST /accounts which
starts creating an account resource.
Call the GET endpoint ( GET /accounts/{id})  which will give the
    status of the account resource. Lets imagine that there are only two
        statuses --> "processing" and "completed". I need to keep polling
        the GET endpoint till the status of the resource changes to
        "completed"
Once the GET /accounts/{id} returns the status completed, i need to
    do return the completed resource.

My main question is how to do this in rxjava using long polling. I looked at some of the links here

https://github.com/ReactiveX/RxJava/issues/3482
https://github.com/ReactiveX/RxJava/issues/448
I wasnt able to understand in these examples was ..how to unsubscribe once a particular predicate was matched..ie. status from GET /accounts/{id} is completed, fetch and end the subscription.

Any help is highly appreciated.

A:

You can use retryWhen() something like shown below.
Considering we have 
private Single<Account> createAccount() // API call to create account
private Single<Account> getAccount(int id) // API call to get account info

When getting account info, if status is "processing", we throw error, which will in turn trigger retryWhen(). And the below code will retry every 5 seconds until the status changes to "completed". Only the getAccount() stream will be retried again.
createAccount()
    .flatMap(
        createdAcc -> getAccount(accountId)
            .flatMap(
                status -> status == "procesing" ?
                          Single.error(new Throwable()) :
                          Single.just(status)
            )
            .doOnError(throwable -> Log.e("", "retrying"))
            .retryWhen(errors -> errors.flatMapSingle(error -> Single.timer(5, TimeUnit.SECONDS)))
    )
    .subscribe();

