简体   繁体   中英

Alternative for observeForever using Transformations.map

I am observing a liveData to do some queries using observeForever inside ViewModel,

  query.observeForever {
      //
    }

the logic is working fine, but i can't remove the observer in onCleared as i have no access to lifecycle from viewModel and i shouldn't, i tried with Transformation.map

 Transformations.map(query){
//
    }

and failed to observe the changes.any suggestions how to use Transformation.map to listen to livedata changes and act on them

You could make your viewmodel extend LifecycleObserver like this -

class MyViewModel() : LifecycleObserver {
   val queryObserver = Observer {
     // do stuff
   }

   @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
   fun onResumed() {
    query.observeForever(queryObserver)
   }

   @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
   fun onPasued() {
    query.removeObserver(queryObserver)
   }
}

Don't forget to add getLifecycle().addObserver(mViewModel) in your Activity!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM