Passing Application to ViewModel in Jetpack Compose

Viewed 777

I have the following inside a @composable function. I am getting an error with the previews. I am not sure this works on a device either.

val context = LocalContext.current
val noteTrainerViewModel = NoteTrainerViewModel(context.applicationContext as Application)

And here is the error:

java.lang.ClassCastException: class com.android.layoutlib.bridge.android.BridgeContext cannot be cast to class android.app.Application
1 Answers

This happens because in preview there's no Application running. You cannot use methods that depend on Application during preview

On a real run this code will work fine

Related