is there a reason I wouldn't be able to use `scope...
# coroutines
r
is there a reason I wouldn't be able to use
scope.launch { channel.send(value) }
instead of
channel.trySendBlocking(value)
to avoid blocking in some callback based API?
j
These are not the same things. Using
scope.launch
would start an asynchronous operation, while
trySendBlocking
would synchronously send the value. If your callback fires many times,
trySendBlocking
would apply some backpressure to the callback's caller, while
scope.launch
would start many coroutines in an unbounded way.
You probably never want to use
scope.launch
in this case. If you don't want backpressure, you can use an unlimited buffer for your channel instead. This is much simpler and doesn't require an extra scope just for this.
r
Thanks, I definitely don't want an unbounded number of coroutines behind launched. I'm not against providing a backpressure strategy, but I would prefer to suspend rather than block when the callback is invoked.
k
To avoid blocking in a callback API, you'll want to adjust the buffer of the channel. Your best options are to conflate it or set the buffer to unlimited. Then you can use trySend and expect it to succeed
j
I would prefer to suspend rather than block when the callback is invoked.
That's not for you to decide, but for the author of the callback-based API. If the callback is not a suspend function, then backpressure works by blocking, and you just have to accept it 😉
☝️ 1
r
Ah, got it! thanks!