2

The Controller + EventBus pattern works very well in Android, but firing events everywhere gets really messy. If a controller gets asks to load the same data multiple times, it's easy to have it start loading the first time, and ignore subsequent requests while its loading, and start listening to future loading requests once it's done loading. How can I do this with RxJava (using MVP presenters?)

Scenario

I have a singleton ColorModel in my android app that loads my favorite color (from multiple sources), as an Observable<String> (String == hexcode).

My ColorPresenter hooks into the ColorModel, converting the String hexcode into a Color object that can be displayed in the ColorView.

These are the main pieces of my logic:

  1. Observable<String> getColor() (from ColorModel)
  2. Observable<Color> getColorForView() (from ColorPresenter)
  3. subscribe() (in ColorView)

Problems

  • #1 is created on every subscription. If I have multiple presenters calling #1, this is very wasteful. I don't want this step repeated (only initiated on the first call, then cached after).
  • When I unsubscribe during onStop(), #2 gets cancelled (desired), but that unsubscription bubbles up to #1 being cancelled too (not desired).
ZakTaccardi
  • 12,212
  • 15
  • 59
  • 107

2 Answers2

0

You can use ConnectedObservables with a replay operator. See the accepted answer at Single Observable with Multiple Subscribers.

Community
  • 1
  • 1
JohnWowUs
  • 3,053
  • 1
  • 13
  • 20
0

You should take a look at operator cache. You can use it and store reference to observable somewhere (like in case of ConnectableObservable).

Be careful, cause you don't have an ability to unsubscribe from observable that was created with cache operator. But in your case that's what you want, because unsubscribing from #2 does not affect #1 lifecycle anymore.