Jitendra
06/20/2022, 3:41 AMFrancesc
06/20/2022, 4:47 AMAdvitiay Anand
06/20/2022, 6:05 AMclass MyViewModel : ViewModel() {
fun useContextToDoSomething(context: Context) {
// Do something
}
class MainActivity : ComponentActivity() {
val viewModel: MyViewModel by viewModels()
setContent {
MyComposable(doWithContext = viewModel.useContextToDoSomething)
}
}
@Composable
fun MyComposable(doWithContext: (Context) -> Unit) {
val context = LocalContext.current
Button(onClick = { doWithContext(context) }) {
Text("Click Me!")
}
}
This way, the context is always fresh, but the functionality is still kept in the viewmodel, away from the UIkotlinforandroid
06/20/2022, 1:37 PMViewModel
can live longer than the View
that uses it. That's why the reference can go stale. The View
gets GC'd and thus its Context
as well. A ViewModel
in Compose is often bound to the NavGraph and thus outlives its View counterpart.