Skip to content

Instantly share code, notes, and snippets.

@featzima
Created October 17, 2019 09:51
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 featzima/c619afcefb57fc074cfda6d3336a58c2 to your computer and use it in GitHub Desktop.
Save featzima/c619afcefb57fc074cfda6d3336a58c2 to your computer and use it in GitHub Desktop.
The BLoC implementation with Kotlin
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