I've got a callback that can be called multiple ti...
# coroutines
r
I've got a callback that can be called multiple times. How do I push the data passed to the callback into a
Channel
?
j
I'm not exactly sure what your question is precisely about. If you're asking this because
channel.send()
is a suspend function, but you're in a regular callback where you can't call it, there is
trySendBlocking
for this purpose - that is if your callback expects the work to be done when you return. Oh, and it assumes you're not on Kotlin/JS either. Otherwise you could play with
trySend
.
More generally, though, if your goal is to wrap a callback-based API (with repeated calls to the callback) into a coroutines approach, you should probably use
callbackFlow { ... }
and turn this API into a
Flow
-based API. You will of course have the same channel issue as above, but you'll benefit from the rest of the "infrastructure".
r
Ah yeah, looks good, thanks.
Yup,
callbackFlow
works as expected. Nice.
🆒 1