Skip to content

Instantly share code, notes, and snippets.

@cfrank
Last active July 5, 2022 09:03
Show Gist options
  • Save cfrank/89472c695b7c896e3c4ddd6ceb7fff5d to your computer and use it in GitHub Desktop.
Save cfrank/89472c695b7c896e3c4ddd6ceb7fff5d to your computer and use it in GitHub Desktop.
Kotlin event bus playground
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*
sealed class AppEvent {
data class Initialized(val timestamp: Long) : AppEvent()
class Bootstrapped() : AppEvent()
data class Loaded(val timestamp: Long) : AppEvent()
}
class EventBus {
private val _events = MutableSharedFlow<AppEvent>()
public val events = _events.asSharedFlow()
public suspend fun invokeEvent(e: AppEvent) = _events.emit(e)
}
class AppLoadModel constructor(
private val eventBus: EventBus
){
public suspend fun initialize() = eventBus.invokeEvent(AppEvent.Initialized(0))
public suspend fun bootstrap() = eventBus.invokeEvent(AppEvent.Bootstrapped())
public suspend fun loaded() = eventBus.invokeEvent(AppEvent.Loaded(1))
}
class AppLoadController constructor(
private val eventBus: EventBus
){
private val scope = CoroutineScope(Dispatchers.Default)
init {
scope.launch {
eventBus.events.collect {
when(it) {
is AppEvent.Initialized -> handleInitialize(it)
is AppEvent.Bootstrapped -> handleBoostrap()
is AppEvent.Loaded -> handleLoaded(it)
}
}
}
}
private fun handleInitialize(e: AppEvent.Initialized) {
println("Handle: initialize ${e.timestamp}")
}
private fun handleBoostrap() {
println("Handle: bootstrap")
}
private fun handleLoaded(e: AppEvent.Loaded) {
println("Handle: loaded ${e.timestamp}")
}
}
fun main() = runBlocking<Unit> {
val eventBus = EventBus()
launch {
delay(100)
val appLoadModel = AppLoadModel(eventBus)
appLoadModel.initialize()
appLoadModel.bootstrap()
appLoadModel.loaded()
}
AppLoadController(eventBus)
println("Starting...")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment