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).

  • Unidirectional Flow: Enforces the Intent ->State pattern.

  • 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)
}
}
}
}
}
}

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.

Constructors

Link copied to clipboard
constructor(initialState: State)

Properties

Link copied to clipboard
open override val effects: Flow<E>
Link copied to clipboard
open override val state: StateFlow<State>

Functions

Link copied to clipboard
open fun addCloseable(closeable: AutoCloseable)
fun addCloseable(key: String, closeable: AutoCloseable)
Link copied to clipboard
protected fun <T> async(block: suspend () -> T, reducer: State.(Result<T>) -> State)

Executes a suspend operation on IO and reduces the result into state.

Link copied to clipboard
protected fun <T> collectFlow(source: () -> Flow<T>, reducer: State.(T) -> State)

Collects a Flow inside the ViewModel scope.

Link copied to clipboard
open override fun dispatch(intent: I)
Link copied to clipboard
protected fun emitEffect(effect: E)

Emits a one-time effect to the UI layer.

Link copied to clipboard
protected suspend fun emitEffectSuspend(effect: E)

Suspended variant of emitEffect.

Link copied to clipboard
Link copied to clipboard
protected abstract suspend fun handleIntent(intent: I)

Handles incoming UI intents.

Link copied to clipboard
protected open fun onCleared()
Link copied to clipboard
protected fun setState(reducer: State.() -> State)

Updates the current state using a reducer function.