2

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?

Krzysztof Skrzynecki
  • 2,345
  • 27
  • 39

1 Answers1

2
  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.

Andrew G
  • 2,596
  • 2
  • 19
  • 26
  • By "display list of views and all of them can be data stream which we would like to subscribe to" I meant view holder are a little bit more complicated then just simple clickable views - they can be e.g. edit text views. Moreover what I proposed doesn't violate any of points which you mentioned - subscription will be passed with event from ViewHolder to activity/fragment, so it won't be lifecycle aware and we won't pass subscription to adapter - adapter won't be aware of those subscriptions. – Krzysztof Skrzynecki Sep 29 '16 at 18:35
  • And btw for what we have I think RxJava is best solution - multiple data sources (view holders) emit data which needs to be combined and throttled - RxJava can easy handle it. – Krzysztof Skrzynecki Sep 29 '16 at 18:37