View on GitHub

PreCompose

Compose Multiplatform Navigation && State Management

ViewModel

Basically the same as Jetpack ViewModel

Setup

Add Dependency

Maven Central

Add the dependency in your common module’s commonMain sourceSet

api("moe.tlaster:precompose-viewmodel:$precompose_version")

Usage

You can define you ViewModel like this:

class HomeViewModel : ViewModel() {

}

With viewModelScope you can run suspend function like what you’ve done in Jetpack ViewModel.

To use ViewModel in compose, you can use the viewModel()

val viewModel = viewModel(keys = listOf(someKey)) {
    SomeViewModel(someKey)
}

When the data that passing to the keys parameter changed, viewModel will be recreated, otherwise you will have the same viewModel instance. It’s useful when your viewModel depends on some parameter that will receive from outside.

NOTE: If you’re using Kotlin/Native target, please use viewModel with modelClass parameter instead.

val viewModel = viewModel(modelClass = SomeViewModel::class, keys = listOf(someKey)) {
    SomeViewModel(someKey)
}

If you need to save and restore state in the ViewModel, you can use SavedStateHolder.

val viewModel = viewModel(modelClass = SomeViewModel::class, keys = listOf(someKey)) { savedStateHolder ->
    SomeViewModel(someKey, savedStateHolder)
}

Then the ViewModel might look like this:

class SomeViewModel(private val someKey: Int?, savedStateHolder: SavedStateHolder) : ViewModel() {
    val someSavedValue = MutableStateFlow(savedStateHolder.consumeRestored("someValue") as String? ?: "")
    
    init {
        savedStateHolder.registerProvider("someValue") {
            someSavedValue.value
        }
    }
    
    fun setSomeValue(value: String) {
        someSavedValue.value = value
    }
}