https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Alireza

12/10/2019, 2:55 PM
Hi, is possible to use coroutines as
EventBus
? i found this gist: https://gist.github.com/svenjacobs/57a21405b2dda4b62945c22235889d4a , but
filter
operator of
openSubscription()
is mark as deprecated!, is there any better sample code?
a

Adam Powell

12/10/2019, 3:12 PM
use
.asFlow()
on the broadcast channel and then operator chain from there instead. Strongly consider using
offer
or declaring your
send
method
suspend
instead of `launch`ing internally. The
filter
followed by
map
for the cast would be better written
.mapNotNull { it as? T }
or
filterIsInstance
EventBus isn't a particularly scalable pattern though; there are probably better ways to approach your problem.
👍 1
4
It's very easy to make a mess, make things hard to debug, and end up with strange latency in unrelated operations. And that's just the tip of the iceberg.
a

Alireza

12/10/2019, 3:52 PM
Thanks @Adam Powell,you are right, i agree that EventBus makes app scalability harden, but at now i have callback hell in my code and i think this is my only solution!, i test below code and seems that do work correctly
Copy code
inline fun <reified T> listen(): Flow<T> {
    return channel.asFlow().filter { it is T }.map { it as T }
}
can you show me an example of using
offer()
or
send()
for my listen method? according to your first suggested method
b

bdawg.io

12/10/2019, 5:37 PM
You can do this to merge the filter and cast into a single operation
asFlow().filterIsInstance<T>()
g

Gerard Klijs

12/10/2019, 7:27 PM
Seems like me for an eventbus you want to have some like a server where state persists, and clients without state. Something like https://axoniq.io/
11 Views