Krzysztof Skrzynecki
Krzysztof Skrzynecki

Reputation: 2525

Use event bus to pass RxJava subscriptions

Currently I'm working on project which is using RxJava together with RxBinding to observe views' changes. It's working really well for fragments and activities where we have easy access to life-cycle events - as it's recommended we bind to data streams on onResume and unbind on onPause.

Lately we've introduces RecyclerView, which display list of views and all of them can be data stream which we would like to subscribe to. The problem which I faced is passing CompositeSubscription object from activity/fragment through adapter down to view holders when they are created. Of course it doesn't work well ViewHolders won't be recreated when user leaves a screen and comes back (onPause and onResume are being called).

The solution would be to make adapter, layout manager (to access existing view holders) life cycle aware, but it require from us to write extra code to pass those subscriptions reference between logic layers.

However one of my colleagues proposed to use event bus, which would be used to pass Subscription in a event to activity/fragment, where they'll be added to CompositeSubscription and all of them will be unsubscribed all together. Moreover we can inform view holder to subsribe themself when user returns.

What do you think about this approach? Are there any pitfalls which I should be aware of in this approach?

Upvotes: 2

Views: 267

Answers (1)

Andrew G
Andrew G

Reputation: 2614

  1. Do not make your Views lifecycle aware. This violates separation of concerns.
  2. Just use clickListeners upon viewBind in the Adapter.
  3. Don't pass the Subscription to the adapter. (The adapter doesn't need to know about it, nor control it's lifecycle) The adapter could just offer an Rx-endpoint that you subscribe to in the (for example) Activity onStart and unsubscribe in onStop. Then Adapter can handle the marshalling of click events on items into an Observable.

Remember: You shouldn't apply RxJava to every problem.

Upvotes: 2

Related Questions