RxJava - Target Requests and UI Updates

The problem I am facing is this. I need to fulfill a couple of requests to the server. Each subsequent request depends on the result of the previous one. They look like this (abbreviated):

Observable<FileUploadResponse> obsFile = api.uploadFile(); Observable<TokenCreateResponse> obsCreateToken = api.createToken(); Observable<PaymentResponse> obsPayment = api.submitOrder(); 

I created one observable using flatMap, which returns a PaymentResponse object or emits onError () if some of the requirements are not met. This works fine, and I get all requests made in one go.

The problem is that I cannot update the interface between these requests. With the current setup, I show the load at the start of the request and hide it when all requests are completed. Is there a way to update the interface between these requests?

I want this: 1. File upload - write a message in the user interface. 2. Creating a token - write a message in the user interface. 3. Sending an order - write a message in the user interface. 4. When everything is complete, hide the run dialog.

My understanding is to release some Observable using onNext () when each API call is complete and then call onComplete () when everything is done. But how do I do this?

+8
android rx-java
source share
1 answer

You can achieve this with doOnNext and PublishSubject . First create a theme and some values:

 public static final int STATUS_UPLOADING = 0; public static final int STATUS_TOKEN = 1; public static final int STATUS_SUBMITTING = 2; public static final int STATUS_DONE = 3; PublishSubject<Integer> status = PublishSubject.create(); public Observable<Integer> getStatusStream() { return status; } 

Then, when you do your download, just submit the value to this question every time:

 status.onNext(STATUS_UPLOADING); return api.uploadFile() .doOnNext(o -> status.onNext(STATUS_TOKEN)) .flatMap(o -> api.createToken()) .doOnNext(o -> status.onNext(STATUS_SUBMITTING)) .flatMap(o -> api.submitOrder()) .doOnNext(o -> status.onNext(STATUS_DONE)) 

Then you can subscribe to Subject and update your interface:

 model.getStatusStream() .subscribeOn(AndroidSchedulers.mainThread()) .subscribe( status -> { view().setMessage(status); }, Throwable.printStackTrace ); 

Alternatively, depending on how you want to architect your application, you can simply invoke update view calls with doOnNext each time. You will probably need to use observeOn to switch between the main and background threads each time.

+9
source share

All Articles