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

ubu

10/07/2019, 2:03 PM
Hi there! I have trouble integrating synchronous code with coroutines, in order to get that broadcasting feature I was able to implement using `RxJava`:
Copy code
class Handler : MessageHandler {

    private val channel = Channel<Message>(1)

    override fun handle(message : Message) {
        // TODO send event.
    }

    fun send(event : Message) {
        
    }

/*
    fun observe() : Channel<Message>
    fun observe() : Flow<Message>
*/
}
When having `RxJava`’s
subjects
, I could call
onNext()
, let observers consume it by exposing some
Observable
. Is there a way to do the same with
Coroutines
? I need to expose some methods that allow to observe stream of events received in
handle(message : Message)
method. Thanks a lot in advance!
z

zak.taccardi

10/07/2019, 2:04 PM
expose your channel into a flow (
consumeAsFlow()
or
receiveAsFlow()
)
send data to teh channel
if you need subject-like behavior
u

ubu

10/07/2019, 2:06 PM
@zak.taccardi, thanks for helping. Could I implement that without marking my method with suspend modifier?
z

zak.taccardi

10/07/2019, 2:07 PM
yes
u

ubu

10/07/2019, 2:10 PM
@zak.taccardi, how do you send events to your channel?
z

zak.taccardi

10/07/2019, 2:12 PM
with
channel.send(..)
if I am in a coroutine or
channel.offer(..)
if I am not
u

ubu

10/07/2019, 2:12 PM
thanks!
z

zak.taccardi

10/07/2019, 2:12 PM
note that if you use
channel.offer(..)
, the Channel’s capacity comes into play
💥 1
u

ubu

10/07/2019, 2:14 PM
could we implement some kind of coroutines bus using channels?
z

zak.taccardi

10/07/2019, 2:17 PM
not just with Channels, you’d need
Flow<T>
Channels are for communicating between coroutines, or into one from outside of one, and
Flow<T>
is for exposing an API of multiple events of
T
Channels are a communication primitive
p

Pablichjenkov

10/07/2019, 3:30 PM
check this for an event bus based on coroutines: https://github.com/Daniil-Pavenko/coroutines-event-pipe
However, although Event Bus is a great architecture on Server Side. Android popular implementations I consider are very poor.
2 Views