Last active
May 12, 2025 10:43
-
-
Save Matikano/f3feb8360a18311c33fe0465648d296b to your computer and use it in GitHub Desktop.
MVI BaseViewModel file template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Main one - ViewModel | |
NAME: MVI BaseViewModell | |
FILE NAME: BaseViewModel | |
EXTENSION: kt | |
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.viewModelScope | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.flow.SharingStarted | |
import kotlinx.coroutines.flow.onStart | |
import kotlinx.coroutines.flow.receiveAsFlow | |
import kotlinx.coroutines.flow.stateIn | |
import kotlinx.coroutines.flow.update | |
abstract class BaseViewModel<STATE, ACTION: UiAction>( | |
initialState: STATE, | |
stateFlowSubscriptionStopTimeoutMillis: Long = STATE_FLOW_SUBSCRIPTION_STOP_TIMEOUT_MILLIS | |
): ViewModel() { | |
protected val _uiState: MutableStateFlow<STATE> = MutableStateFlow(initialState) | |
val uiState = _uiState | |
.onStart { loadData() } | |
.stateIn( | |
scope = viewModelScope, | |
started = SharingStarted.WhileSubscribed(stateFlowSubscriptionStopTimeoutMillis), | |
initialValue = initialState | |
) | |
protected val _uiEvent = Channel<UiEvent>() | |
val uiEvent = _uiEvent.receiveAsFlow() | |
val currentState: STATE | |
get() = uiState.value | |
abstract fun loadData() | |
abstract fun onAction(action: ACTION) | |
companion object { | |
private const val STATE_FLOW_SUBSCRIPTION_STOP_TIMEOUT_MILLIS = 5000L | |
} | |
} | |
2. UiEvent marker interface | |
FILE NAME: UiEvent | |
EXTENSION: kt | |
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end | |
interface UiEvent | |
3. UiAction marker interface | |
FILE NAME: UiAction | |
EXTENSION: kt | |
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME} #end | |
interface UiAction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment