1

I have this question that I have been searching for but could not find a solution (or maybe I cannot make the solution based on other answers).

My problem is that I need to find a way to wait for an observable (with its own subscriber) and wait for another observable (with its own subscriber) to finish.

This is the scenario:

obs1 -> retryWith(tokenAuthenticator) -> subscriber1 -> Update UI

obs2 -> Needs to wait for obs1 to get new token -> subscriber2 -> Update UI

My main concerns is that I need two subscribers. For my point of view obs1 and obs2 run in parallel but needs to check if the obs1 finish with new session tokens. Maybe this is not the main purpose of RxJava.

Obs1 connect to an HTTP connection and get a Json with data to fill in the UI and the same for obs2 but with other json and other information to fill in the UI.

The only problem for me is that my session token expires every 5 minutes and when I try to get new ones obs2 already make the call with expired session tokens.

The simple solution is to execute obs2 in the onComplete() subscriber1 but I know it has to be a better solution for this, using RxJava.

Nicolas Jafelle
  • 2,661
  • 2
  • 24
  • 30
  • Rxjava gives you various Operators that can help you, you can try with those operators for eg. retry, retrywhen, debounce etc – Raut Darpan Dec 07 '16 at 10:14
  • if the problem only in token refreshing, than you can try native `Authenticator ` from okhttp client i described it in other question: http://stackoverflow.com/questions/40762911/call-another-retrofit-call-on-subject-emission/40771313#40771313 – borichellow Dec 07 '16 at 22:33

1 Answers1

2

Look at zip which will allow you to combine the results of two observables (running in parallel if you want). Here's an example:

obs1.subscribeOn(Schedulers.io())
    .zipWith(obs2.subscribeOn(Schedulers.io()), (x,y) -> new Both(x,y))
    .doOnNext(both -> updateUI(both))
    .subscribe();
Pang
  • 9,564
  • 146
  • 81
  • 122
Dave Moten
  • 11,957
  • 2
  • 40
  • 47
  • Dave, Thank you for your big help. I already saw the zip operator, is it the same zip and zipWith? Is it a good solution to create a Pair of two results to do this and use the same subscriber? I am really new in Rx. – Nicolas Jafelle Dec 07 '16 at 13:34
  • Using one subscriber over two subscribers is a good idea because you get increased control over behaviour on error for starters (one failure stops both observables for example). – Dave Moten Dec 07 '16 at 19:43
  • Dave, This actually really works but I have a question regarding the Schedulers.io(). For every observable if you subscribe on Schedulers.IO means it will run in different threads? or it is redundant? Thanks – Nicolas Jafelle Feb 12 '17 at 03:58
  • After doing some test, it seems that use subscribeOn for each observable make the chain run in parallel while using only one subscribOn seems doing it sequentially. – Nicolas Jafelle Feb 12 '17 at 05:05