Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to dispose() Publishers created using LiveDataReactiveStreams

Let's say I have an Flowable that is shared among different parts of the application.

In each fragment where I want to observe it, I convert it to a LiveData with LiveDataReactiveStreams.fromPublisher to avoid leaks and crashes. I now have a LiveData that wraps my Flowable.

I then pass the LiveData to my ViewModel (in the ViewModelFactory). As far as I understand, I can go ahead and use the LiveData without worrying about leaks.

Now, instead of observing the LiveData directly, I am tempted to convert it back to a Flowable with LiveDataReactiveStreams.toPublisher and Flowable.fromPublisher and subscribe to the Flowable instead. This is now a Flowable that wraps a LiveData which wraps a Flowable

My question is: Do I have to worry about disposing the subscriptions to this Flowable? My hope is that the LiveData will act as a "barrier", preventing my context to leak back up to the root Flowable, but I am not so sure about that.

In other words:

  1. Flowable A exists in a global context
  2. In each fragment, A is wrapped in LiveData B which is set as a property of the fragments ViewModel
  3. When normally I would observe LiveData B, I instead wrap it in Flowable C
  4. I subscribe to Flowable C and ignore the returned disposable

Will views accessed in C leak up to A when the fragment is destroyed?

like image 497
Gustav Karlsson Avatar asked Dec 19 '17 10:12

Gustav Karlsson


People also ask

What is LiveDataReactiveStreams?

LiveDataReactiveStreams is a class provided as part of Google's Jetpack components. To use it, you need to add the ReactiveStreams dependency to your project.

What is live data in Kotlin?

LiveData is a wrapper that can be used with any data, including objects that implement Collections , such as List . A LiveData object is usually stored within a ViewModel object and is accessed via a getter method, as demonstrated in the following example: Kotlin Java.


1 Answers

Considering the current implementation, you still need to care for the subscriptions manually. The lifecycle is only used for handling the observation of the live data.

mLiveData.observe(mLifecycle, LiveDataSubscription.this);

The observation is only canceled automatically when a non-positive amount of items was requested and an error is sent. This then disposes the subscription. Since the producer never completes it'll never dispose the subscription by itself and thus you'll leak the subscription if you don't dispose it yourself.

like image 101
tynn Avatar answered Oct 17 '22 01:10

tynn