Possible newbie question: does it make sense for r...
# coroutines
f
Possible newbie question: does it make sense for regular threads and coroutines to communicate/cooperate and what's the best way to achieve that?
g
Coroutines use threading for dispatching callbacks and have CoroutineDispatcher abstraction that can be implemented with threads. So what is your question? Imo use of pure threads is too low level for most cases and I would prefer to use coroutunes instead or at least thread pool from java
f
For example do you see a case for threads and coroutines to communicate through channels?
g
Yes, it's possible, I just not sure why I need thread in this situation
But if it's some kind case when you have only thread for some reason, you can pass channel to thread and use offer to send value to channel without suspension
f
OK that was part 1 of my question, so you don't see a reason to have a thread communicate with a coroutine.
offer
doesn't block the thread though, is there a way to synchronize threads and coroutines? I guess
offer
would always fail on unbuffered channels
Maybe an example is integrating JVM but non-Kotlin code with coroutines-based Kotlin code
g
I just don't see why would I like to use raw thread (except some sort library development or other low level things). You always can use any technique for thread sync to use with coroutines. Coroutines is not a magic thing after all. Offer not always fail, bit may fail, yes. It's just an example of API that doesn't require suspension. Maybe you have some particular case? In case of other JVM languages I would just use some coroutine adapter for CompletableFuture or any promise-like primitive to work with coroutines.
b
You could have your coroutines-based Kotlin API return other non-Kotlin APIs to represent the async nature of the coroutines (ie,
CompletableFuture
)
Copy code
fun doSomething() = async { doCoroutine() }.asCompletableFuture()
👍 1
g
Yes, that exactly what I mean when mentioned "adapter" 👍. That probably better idea to use some more standard async primitive for language
l
@Fabio Tudone You have
sendBlocking(…)
to send something from blocking world to coroutine world through a channel
2
e
You’d be better of with
fun doSomething() = future { doCoroutine() }
as opposed to
async ( ... }.asCompletableFuture()
. The former is more efficient.
👍 2
d
would that be a case of premature optimization based on implementation details though? especially considering the instability of the library, is that something that is guaranteed?
e
It is a case of clearly expressing your intent in your code. When you write
future { ... }
you immediately make it clear to the reader that you are planning to return a
CompletableFuture
. No need to read to the end of the code to learn that.
1
👍 1