Norbi
02/29/2024, 10:46 AMMutableSharedFlow
):
interface InProcessEventBus<E: Any> {
suspend fun events(): Flow<E>
suspend fun publish(event: E)
}
What I would like to achieve is to create a "view" of this event bus to handle only specific types of events, like:
val globalEventBus: InProcessEventBus<Any> = ...
val constrainedEventBus: InProcessEventBus<SomeCustomEventClass> = globalEventBus // Do something with globalEventBus to make this compile
So the constrainedEventBus
would be a view of the less specific globalEventBus
, allowing only to publish and listen to more specific event types.
Although I think this "subtyping" would be correct, the compiler does not think so 🙂
Currently my best solution is an unsafe cast but I hope you have a better idea:
@Suppress("UNCHECKED_CAST")
fun <E: B, B: LocalEvent> InProcessEventBus<B>.constrain(): InProcessEventBus<E> = this as InProcessEventBus<E>
val constrainedEventBus = globalEventBus.constrain<SomeCustomEventClass, _>()
Thanks.ephemient
02/29/2024, 11:36 AMconstrainedEventBus.events().collect { event: SomeCustomEventClass ->
would crash when
globalEventBus.publish(NotSomeCustomEventClass())
is calledephemient
02/29/2024, 11:46 AMinline fun <reified E: Any> InProcessEventBus<in E>.constrain(): InProcessEventBus<E> =
object : InProcessEventBus<E> {
override val events: Flow<E>
get() = this@constrain.flow().filterIsInstance<E>()
override fun publish(event: E) {
this@constrain.publish(event)
}
}