推送新数据时实时数据观察器停止 activity

Live data observer stop when push new activity

我有两个 Activity,每个都有它的 ViewModel,我需要让第一个 Activity 实时数据观察者在推送到新的 Activity 时保持 运行 ], 当前发生的是第二次启动时 Activity 观察者停止工作。

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)

                }
            }

        }
    })
}

怎样才能一直观察到第一个Activity的新数据?

您可以使用 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)。在 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)