观察实时数据并在 jetpack compose 中导航

Sus*_*apa 7 android kotlin android-jetpack-navigation android-jetpack-compose

我刚刚开始学习jetpack compose。我有一个非常基本的问题。我的 ViewModel 有一个 SingleLiveEvent,我用它导航到另一个屏幕。

private val _navigateToDetails: SingleLiveEvent<Movie> = SingleLiveEvent()
val navigateToDetails: MutableLiveData<Movie> = _navigateToDetails
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用 Livedata 作为状态来发出 UI,但如何使用它来触发可组合项中的某些操作。

以前我习惯于viewLifecycleOwner像任何人一样观察国家。

viewModel.navigateToDetails.observe(viewLifecycleOwner) {
    // navigate to details
}
Run Code Online (Sandbox Code Playgroud)

我如何在 compose 中实现同样的目标。我不知道这是否可能。也许我没有以写作的方式思考这个问题。任何帮助,将不胜感激。

Ric*_*per 1

实际上,在compose中我们使用mutableStateOf()LiveData。在视图模型中,您可以将数据持有者的类型从 LiveData 更改为 mutableStateOf(...) ,这将允许您直接在可组合项中使用它,而无需显式调用observe()

假设您希望在视图模型中存储任何类型的整数,并根据该整数更新可组合项的状态。

在你的视图模型中,

var mInteger by mutableStateOf (0) //'by' helps treat state as data

fun updateMInteger(newValue: Int){
mInteger = newValue
}
Run Code Online (Sandbox Code Playgroud)

在您的 Composable 中,直接调用viewmodel.mInteger并像这样构建 Compose,自动更新 UI,前提是从 Composable 中读取 mInteger

喜欢

Text(viewModel.mInteger)
Run Code Online (Sandbox Code Playgroud)

  • 我认为你没有明白这个问题。我并不是试图发出 UI,而是试图在可组合项中的实时数据发生变化时触发一些代码(可能是 lambda)。我尝试触发一些代码并且它起作用了,但问题是它的行为不像 SingleLiveData 并且每次我返回到上一个屏幕时都会触发该事件。 (2认同)