muliyul
02/03/2025, 10:14 PM@Singleton
class EventBus {
private val events = MutableSharedFlow<Any>()
suspend fun publish(event: Any) {
events.emit(event)
}
@OptIn(DelicateCoroutinesApi::class)
fun <T : Any> subscribe(clazz: KClass<T>, onEvent: suspend (T) -> Unit) = GlobalScope.launch {
events.filterIsInstance(clazz).collect { event ->
ensureActive()
onEvent(event)
}
}
}
I used GlobalScope.launch
because it is supposed to live as long as the server is up.
Do you see any issues with this implementation?Zach Klippenstein (he/him) [MOD]
02/03/2025, 10:43 PMGlobalScope
is great for making code untestableZach Klippenstein (he/him) [MOD]
02/03/2025, 10:45 PMsubscribe
? That thing should be responsible for the lifecycle of the subscription. Even if that happens to be "the lifetime of the process" in production, that assumption should not be hard-coded into something like an event busmuliyul
02/03/2025, 11:11 PMmuliyul
02/03/2025, 11:13 PM@Singleton
class CreateOrderUseCase @Inject constructor(
...
private val eventBus: EventBus
) : UseCase {
init {
eventBus.subscribe(PaymentReceivedEvent::class, ::onPaymentReceived)
}
Zach Klippenstein (he/him) [MOD]
02/03/2025, 11:13 PMkevin.cianfarini
02/03/2025, 11:32 PMkevin.cianfarini
02/03/2025, 11:32 PMgildor
02/04/2025, 6:48 AMgildor
02/04/2025, 6:49 AM