Last active
March 24, 2021 22:41
-
-
Save cbedoy/baf589e8e85962a45fafc892b8479d19 to your computer and use it in GitHub Desktop.
This file contains 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
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