Skip to content

Instantly share code, notes, and snippets.

@cbedoy
Last active March 24, 2021 22:41
Show Gist options
  • Save cbedoy/baf589e8e85962a45fafc892b8479d19 to your computer and use it in GitHub Desktop.
Save cbedoy/baf589e8e85962a45fafc892b8479d19 to your computer and use it in GitHub Desktop.
typealias Producer<T> = suspend (Flow<T>) -> Unit
abstract class BaseMVIViewModel<State, Intent>(
initialState: State
) : ViewModel(){
private val intentChannel = Channel<Intent>(Channel.UNLIMITED)
private var _state = MutableStateFlow(initialState)
open val state: StateFlow<State>
get() = _state
abstract suspend fun onCollect(intent: Intent, producer: Producer<State>)
abstract val tagLogger: String
fun perform(intent: Intent){
intentChannel.offer(intent)
}
init {
viewModelScope.launch {
handleIntents()
}
}
private suspend fun handleIntents(){
intentChannel.consumeAsFlow().collect { intent ->
log("ViewModel", "$tagLogger.handleIntent($intent)")
onCollect(intent){ flow ->
flow.collect { newState ->
log("ViewModel", "$tagLogger.collect($newState)")
_state.value = newState
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment