rook
05/30/2019, 7:43 PMsuspend fun waitForUpdates(): ReceiveChannel<Update> = produce {
onUpdateHook { update ->
send(update)
}
}
fun startWaitingForUpdates() {
launch {
waitForUpdates().onReceive { update ->
doUpdate(update)
}
}
}streetsofboston
05/30/2019, 7:53 PMsuspendCoroutine call in waitForUpdates.
fun CoroutineScope.waitForUpdates(): ReceiveChannel<Update> = produce {
onUpdateHook { update ->
send(update)
suspendCoroutine<Nothing> { /* do nothing */ }
}
}
fun CoroutineScope.startWaitingForUpdates() {
launch {
waitForUpdates().apply {
select {
onReceive { update ->
doUpdate(update)
}
}
}
}
}rook
05/30/2019, 7:59 PMsuspendCoroutine<Nothing> { /* do nothing */ }
^ this right here was the missing link, thank you!streetsofboston
05/30/2019, 8:03 PMfun CoroutineScope.waitForUpdates(): ReceiveChannel<Update> = produce {
suspendCoroutine<Unit> { cont ->
onUpdateHook { update ->
send(update)
}
onUpdateTermination { error ->
if (error != null) {
cont.resumeWithException(error)
}
else {
cont.resume(Unit)
}
}
}
}rook
05/30/2019, 8:07 PMDico
05/30/2019, 9:45 PMsend won't work in some of these contexts, use offer with a conflated channel.rook
05/30/2019, 9:54 PMstreetsofboston
05/30/2019, 9:57 PMonUpdateHook looks like. You can make its lambda-parameter suspend (and make it an extension-function of CoroutineScope) if synchronization is important. Otherwise, just call offer like Dico said 🙂rook
05/30/2019, 10:13 PMonUpdateHook. Thanks for all the help!rook
05/30/2019, 10:36 PMproduce without a CoroutineScope?
I’m trying to get my repository interface to return a channel, but if I declare waitForUpdates() as an extension of CoroutineScope, I can’t call the function unless it’s from within the context of the repository objectbdawg.io
05/30/2019, 11:03 PMChannel() functionbdawg.io
05/30/2019, 11:03 PMproduce and actor are implementations that ensure that the Channel's lifecycle is tied to the lifecycle of your coroutine so it doesn't leakrook
05/30/2019, 11:07 PMsuspend function is invoked?streetsofboston
05/30/2019, 11:38 PMsuspend fun waitForUpdates(): ReceiveChannel<Update> = coroutineScope { ... }.
The lambda of the coroutineScope has a this receiver that is a CoroutineScope instance.