Whats the recommended way of initializing a viewmo...
# compose-android
z
Whats the recommended way of initializing a viewmodel in compose that relies on network data? my current method is like this. Surely theres a much better way to do this? loadVideo is just a suspending function
Copy code
@Composable
fun PlayerScreen(
    viewModel: PlayerViewModel = koinViewModel(),
    navController: NavController<Destination>,
    videoId: String? = null
) {
Copy code
LaunchedEffect(Unit) {
        if (viewModel.video == null && videoId != null) viewModel.loadVideo(videoId)
    }
a
I think one drawback of this approach is that you go to another screen and come back again your loadVideo will be called else you need to add these conditions at ui layer before calling the method better pass videoId as constructor param of ViewModel, and use the init block loadVideo is just a suspending function - better to not expose suspending methods from viewmodel as it will be now tied to view lifecycle, rather use viewmodelscope inside viewmodel only
z
Oh I accidentally said loadVideo is suspending, but it's actually not
f
It would be preferable if all this is in the viewmodel. If the video id is a navigation argument in the AAC navigation you can retrieve it in the viewmodel. Prefer your UI not to control the viewmodel.
z
I'm not familiar with "AAC" could you explain what that is or refer me to something?
c
AAC == "Android Architecture Components"