ViewModel and CompositeDisposable
In this article I further describe my work on the demonstration project Timer.
Changes since last episodes
I got rid of some of the elements of the DSL introduced in the last episode, as they were too confusing for me.
The main reason I write the present article is that I discovered a way to handle RxJava’s Disposable
s directly inside the ViewModel
that scopes the entire Activity
. Thanks to that change I do not have to write any code in the Activity
or Fragment
that would initiate updating the LiveData
.
What hasn’t changed
I still demonstrate the use of two ViewModel
s that are Fragment
-specific. Changes described in the present article do not apply to them, as I want to retain their form close to the original, for the sake of comparison.
The new ViewModel
This is the base class of the ViewModel
that is being discussed in the present article:
It creates one private instance of CompositeDisposable
that is disposed when the ViewModel
is cleared. It also has one protected
function that lazily creates an instance of MutableLiveData
. It requires passing an instance of Observable
and subscribes to it.
Please remember to define the return type of disposableLiveData()
as Lazy<LiveData<T>>
. By doing this you hide the real type of the MutableLiveData()
created here, and therefore it will be seen as immutable by the code that is using it.
This is the way in which the above class is extended:
The ViewModel
initiates lazily two instances of LiveData
and creates a CompositeDisposable
. The rest of the code of the Timer
is described in the first episode of this series.
Observing
This is the way in which the new ViewModel
is observed. Please note that the below snippet also, for comparison, shows the line of the code that do not use the design pattern proposed by the present article:
Donations
If you’ve enjoyed this article, consider donating some bitcoin at the address below. You may also look at my donations page.
BTC: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp