简体   繁体   English

如何访问在 Android Jetpack Compose 中注册到 MainActivity 的 ViewModel?

[英]How to access ViewModel that is registered with MainActivity in Android Jetpack Compose?

Android documentation https://developer.android.com/topic/libraries/architecture/viewmodel details the creation and remember/retrieval of ViewModel instance that is registered with MainActivity . Android 文档https://developer.android.com/topic/libraries/architecture/viewmodel详细说明了使用MainActivity注册的ViewModel实例的创建和记住/检索。

My question is - how can I access this viewModel instant from other ViewModel or from @Compose function?我的问题是 - 如何从其他ViewModel@Compose viewModel即时访问此 viewModel?

I have tried code我试过代码

private val sessionViewModel: SessionViewModel by viewModels()

both in my classes descending from ViewModel and in @Composable functions, but viewModels() function is not available there.在我从ViewModel@Composable函数下降的类中,但viewModels() function 在那里不可用。

He is how I have done registration:他是我如何完成注册的:

class MainActivity : AppCompatActivity() {
    //...
    val sessionViewModel: SessionViewModel by viewModels<SessionViewModel>()
}

From a Composable, you would access you viewModel like this:从 Composable 中,您可以像这样访问您的 viewModel:

    @Composable
    fun MyScreen(
    viewModel: MyViewModel = viewModel()
    ) {
    // use viewModel here
    }

Source 资源

As far as I know, you cannot access a viewModel from another viewModel, but see comment from Martin Marconcini below.据我所知,您无法从另一个视图模型访问视图模型,但请参阅下面 Martin Marconcini 的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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