Qasem M. Zreaq
Qasem M. Zreaq

Reputation: 139

Live data observer stop when push new activity

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?

Upvotes: 1

Views: 957

Answers (1)

Sergio
Sergio

Reputation: 30595

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)

Upvotes: 1

Related Questions