Last active
February 21, 2021 23:56
-
-
Save danylovolokh/0355863ff33568dc843a to your computer and use it in GitHub Desktop.
Server polling and retry operations when failed. With Retrofit and RxJava.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is a class that should be | |
* mapped on your json response from the server | |
*/ | |
class ServerPollingResponse { | |
boolean isJobDone; | |
@Override | |
public String toString() { | |
return "isJobDone=" + isJobDone; | |
} | |
} | |
Subscription checkJobSubscription = mDataManager.pollServer(inputData) | |
.repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() { | |
@Override | |
public Observable<?> call(Observable<? extends Void> observable) { | |
Log.v(TAG, "repeatWhen, call"); | |
/** | |
* This is called only once. | |
* 5 means each repeated call will be delayed by 5 seconds | |
*/ | |
return observable.delay(5, TimeUnit.SECONDS); | |
} | |
}) | |
.takeUntil(new Func1<ServerPollingResponse, Boolean>() { | |
@Override | |
public Boolean call(ServerPollingResponse response) { | |
/** Here we can check if the responce is correct and if we should | |
* finish polling | |
* We finish polling when job is done. | |
* In other words : "We stop taking when job is done" | |
*/ | |
Log.v(TAG, "takeUntil, call response " + response); | |
return response.isJobDone; | |
} | |
}) | |
.filter(new Func1<ServerPollingResponse, Boolean>() { | |
@Override | |
public Boolean call(ServerPollingResponse response) { | |
/** | |
* We are filtering results if we return "false". | |
* Filtering means that onNext() will not be called. | |
* But onComplete() will be delivered. | |
*/ | |
Log.v(TAG, "filter, call response " + response); | |
return response.isJobDone; | |
} | |
}) | |
.subscribe( | |
new Subscriber<ServerPollingResponse>() { | |
@Override | |
public void onCompleted() { | |
Log.v(TAG, "onCompleted "); | |
} | |
@Override | |
public void onError(Throwable e) { | |
Log.v(TAG, "onError "); | |
} | |
@Override | |
public void onNext(ServerPollingResponse response) { | |
Log.v(TAG, "onNext response " + response); | |
// Do whatever you need. Server polling has been finished | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment