KMviViewModel
abstract class KMviViewModel<State, I, E>(initialState: State) : ViewModel, MviViewModel<State, I, E> (source)
Base implementation of a strict MVI (Model-View-Intent) ViewModel.
This class provides the foundational logic for managing state and side effects in a thread-safe and lifecycle-aware manner. It is designed to work seamlessly with KScreen.
Key Features:
State Management: Uses a StateFlow to hold and emit immutable state objects.
Side Effects: Uses a buffered SharedFlow for one-shot effects (e.g., navigation).
Async Helpers: Built-in async and collectFlow for coroutine-safe data fetching.
Implementation Example:
data class ProfileState(val name: String = "", val isLoading: Boolean = false)
sealed interface ProfileIntent : Intent { data object Load : ProfileIntent }
sealed interface ProfileEffect : Effect { data class ShowError(val msg: String) : ProfileEffect }
class ProfileViewModel(val repo: Repo) : KMviViewModel<ProfileState, ProfileIntent, ProfileEffect>(ProfileState()) {
override suspend fun handleIntent(intent: ProfileIntent) {
when (intent) {
ProfileIntent.Load -> {
setState { copy(isLoading = true) }
async({ repo.getName() }) { result ->
result.onSuccess { copy(name = it, isLoading = false) }
.onFailure {
emitEffect(ProfileEffect.ShowError("Failed"))
copy(isLoading = false)
}
}
}
}
}
}Content copied to clipboard
Parameters
initialState
The state emitted immediately on subscription.
Type Parameters
State
The immutable UI state data class.
I
The Intent type representing user actions.
E
The Effect type for one-shot side effects.
Properties
Functions
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Emits a one-time effect to the UI layer.
Link copied to clipboard
Suspended variant of emitEffect.
Link copied to clipboard
Link copied to clipboard
Handles incoming UI intents.