Created
October 17, 2019 09:51
-
-
Save featzima/c619afcefb57fc074cfda6d3336a58c2 to your computer and use it in GitHub Desktop.
The BLoC implementation with Kotlin
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
abstract class Bloc<State, Event> : ViewModel() { | |
private val timber by lazy { Timber.tag(javaClass.simpleName) } | |
private val events = Channel<Event>(Channel.UNLIMITED) | |
private var _currentState = ConflatedBroadcastChannel(initialState) | |
protected val currentState: ReceiveChannel<State> | |
get() = _currentState.openSubscription() | |
abstract val initialState: State | |
abstract fun mapEventToState(event: Event): Flow<State> | |
init { | |
viewModelScope.launch(Dispatchers.Default) { runDispatchLoop() } | |
} | |
fun dispatch(event: Event) { | |
events.offer(event) | |
} | |
private suspend fun runDispatchLoop() { | |
for (event in events) { | |
timber.v("event: $event") | |
mapEventToState(event) | |
.onEach { state -> timber.v("state: $state") } | |
.onEach(_currentState::send) | |
.collect() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment