Home > Blockchain >  Live data observer stop when push new activity
Live data observer stop when push new activity

Time:01-13

I have two Activities, each one have its ViewModel, and I need to make the first Activity live data observer keep running when push to the new Activity, the current happening is when launch second Activity the observer stop working.

private fun observer() {
    viewModel.myData.observe(this, {
        when (it) {
            it -> {
                it.let {
                    val intent = Intent(Events.DATA_EVENT.value)
                    intent.putExtra("data", it)
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

                }
            }

        }
    })
}

How can I always observe the new data in first Activity?

CodePudding user response:

You can use observeForever(Observer) method. An observer added via observeForever(Observer) is considered as always active and thus will be always notified about modifications. For those observers, you should manually call removeObserver(Observer). In Activity:

val observer = Observer<String> { // use your data class instead of String generic type
    // ...
}

// in onCreate() method
viewModel.myData.observeForever(observer)

// in onDestroy() method
viewModel.myData.removeObserver(observer)
  •  Tags:  
  • Related