1
votes

i am using AndroidViewModel and returning stream of data be it Observable or LiveData, so far its going well, i see there is a method in ViewModel class, onCleared() document says

This method will be called when this ViewModel is no longer used and will be destroyed.It is useful when ViewModel observes some data and you need to clear this subscription to prevent a leak of this ViewModel.

I have a scenario where i return Single<ApiResponse> from retrofit do some .map() in ViewModel and return response as Single<ToBeShownOnUiResponse> i subscribe this in View i.e Fragment. I add subscriber to CompositeDisposable and thereafter clear it onStop fragment. When i navigate from LoginActivity(hold signin/signup/passwordreset fragment) to HomeActivity(hold tablayout with other fragments) i dont see the logs written in onCleared() method of ViewModel class. Is something wrong i am doing or i did a complete mess of it.

My query here is that in what way onCleared() is helpful to me. What separate code or cleanup i should be writing in it?

Usage: When i need string resource then i use AndroidViewModel(Formatting some api response according to string resource present in xml) and when only api call require i use ViewModel.

1
you can dispose the disposable in onCleared in your viewmodel. a nice blog if you need the code proandroiddev.com/… - Raghunandan
correct, but as per google samples they have written disposable in View(Activity/Fragment) and not in ViewModels - silentsudo
that can also work what you do is unsubscribe when activity/fragment is destoryed - Raghunandan

1 Answers

0
votes

One example use case of calling onCleared is when you use a ViewModel for in-app billing. In that case, it is natural to let the BillingClient to persist as long as an activity (In the below example I used Application), for example like this:

class BillingViewModel(application: Application)
  : AndroidViewModel(application), PurchasesUpdatedListener, BillingClientStateListener {

  private lateinit var playStoreBillingClient: BillingClient

  init {
    playStoreBillingClient = BillingClient.newBuilder(application.applicationContext)
        .enablePendingPurchases()
        .setListener(this).build()
    playStoreBillingClient.startConnection(this)
  }

...

 override fun onCleared() {
    super.onCleared()
    playStoreBillingClient.endConnection()
}