在 Jetpack compose 如果我不使用 Fragment 或 Activity 的话在哪里创建 ViewModel

问题描述 投票:0回答:1

我正在为我的电子商务应用程序使用 Stream Chat SDK。在 Stream Chat 的文档中,他们正在使用 Activity,他们可以通过使用像这样的 viewModels 委托轻松声明他们的默认视图模型:

TL;DR:如何像我们在 Activity 或 Fragments 中那样在可组合项中创建 viewModel:

val channelListViewModel: ChannelListViewModel by viewModels { ... }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Your ViewModel instance
    val channelListViewModel: ChannelListViewModel by viewModels { ... }
    
    setContent {
        ChatTheme { // Theme wrapper
            ChannelList(
                modifier = Modifier.fillMaxSize(),
                viewModel = channelListViewModel,
                onChannelClick = {
                    // Open the MessagesScreen
                },
            )
        }
    }
} 

但是因为我使用的是 Jetpack Compose Navigation,所以除了 MainActivty 之外我没有使用任何活动,而且我也没有使用任何片段。所以我不能在我的屏幕可组合项中使用 viewModels 委托,也不能声明必要的流聊天 viewModel。

我试过的

  • 试过
    composable
    viewModel像这样
    val channelListViewModel: ChannelListViewModel = viewModel()

但它抛出错误:

java.lang.RuntimeException: Cannot create an instance of class io.getstream.chat.android.compose.viewmodel.channels.ChannelListViewModel

My Screen Composable,我使用 Stream Chat 的组件并需要声明它们的 viewModel

@Composable
fun ChannelsScreen(
    context : Context,
    navController: NavController,
    viewModel : ChannelsViewModel = hiltViewModel()
) {
    LaunchedEffect(key1 = true) {
        viewModel.onEvent(ChannelsEvent.ConnectUser)
    }

    val channelListViewModel: ChannelListViewModel = viewModel() //<-- Throws Exception

    ChatTheme {
        ChannelList(
            modifier = Modifier.fillMaxSize(),
            viewModel = channelListViewModel //<-- Their default viewModel,
            onChannelClick = {
                // Open the MessagesScreen
            },
        )
    }
}
android kotlin mvvm android-jetpack-compose android-viewmodel
1个回答
0
投票

嘿,如果你的

view model
不包含任何参数,你可以在你的组合导航文件中这样写👇

val channelListViewModel: ChannelListViewModel = viewModel()

但是,如果它包含参数并且您正在使用匕首柄,那么您可以使用

compose-hilt-navigation
库并在您的可组合函数中提供
viewmodel's
实例,就像这样。

@Composable
fun Test(
viewModel : ChannelListViewModel = hiltViewModel()
){ }
© www.soinside.com 2019 - 2024. All rights reserved.