Idiomatic way to add Coroutine scope to a function...
# coroutines
r
Idiomatic way to add Coroutine scope to a function that is already an extension function of something else? Take it as a parameter?
e
Can you give an example?
1
(with some background on how this comes to be)
r
@elizarov I have a utility function like this:
Copy code
suspend fun Flowable<ByteBuffer>.toByteReadChannel(scope: CoroutineScope) = scope.writer(scope.coroutineContext, autoFlush = true) {
  try {
    this@toByteReadChannel.consumeEach {
      channel.writeFully(it)
    }
  } catch (e: Throwable) {
    channel.close(e)
  }
}.channel
Note here I have explicitly passed scope, since its already an extension of
Flowable<ByteBuffer>
. Is there a better approach?
I also have the opposite
toFlowable
function, implemented like this:
Copy code
suspend fun DataChannelProvider.toFlowable(scope: CoroutineScope): Flowable<ByteBuffer> = scope.rxFlowable(Dispatchers.Default) {
  this@toFlowable().lookAheadSuspend {
    consumeEachRemaining {
      // we have to make a copy as the ByteBuffer here comes from a reused ring buffer
      this@rxFlowable.send(it.copy())
      true
    }
  }
}
z
Since your function is already a
suspend
function, you can use
coroutineContext
to get the scope from the current coroutine.
Copy code
suspend fun Flowable<ByteBuffer>.toByteReadChannel() = coroutineContext {
  writer(…
r
I think you meant
coroutineScope { ... }
but otherwise, ah, thank you @Zach Klippenstein (he/him) [MOD]
FYI @Zach Klippenstein (he/him) [MOD] this didn't work... see the recent thread in #coroutines ...