Skip to content

Instantly share code, notes, and snippets.

@motorro
Created August 13, 2022 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motorro/7248355b6398c20c8f7c602cd655b1d5 to your computer and use it in GitHub Desktop.
Save motorro/7248355b6398c20c8f7c602cd655b1d5 to your computer and use it in GitHub Desktop.
Lifecycle-aware view-model
class WithIdleViewModel : ViewModel() {
/**
* Creates initial state for state-machine
* You could process a deep-link here or restore from a saved state
*/
private fun initStateMachine(): CommonMachineState<SomeGesture, SomeUiState> = InitialState()
/**
* State-machine instance
*/
private val stateMachine = FlowStateMachine(::initStateMachine)
/**
* UI State
*/
val state: SharedFlow<SomeUiState> = stateMachine.uiState
init {
// Subscribes to active subscribers count and updates state machine with corresponding gestures
stateMachine.mapUiSubscriptions(
viewModelScope,
onActive = { SomeGesture.OnActive },
onInactive = { SomeGesture.OnInactive }
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment