https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

eygraber

10/20/2017, 6:41 PM
Hello all, I've been reading the docs and the KEEP, but I'm not sure I fully understand what coroutines offer. The example I've been keeping in my head is a server that responds to all requests with a randomly selected quote that it retrieves from a remote service. The call to that service and the response sent back to the client is done on a separate thread than the one the request comes in on. Using vanilla executors we would pass a
Runnable
that makes the network call and writes the response. Using Rx it would look something like:
Copy code
quoteService
    .getQuote()
    .flatMap(response::write)
    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
    .subscribeBy(
      onSuccess = {},
      onError = {}  
    )
I'm not great with coroutines, but I assume it would look something like:
Copy code
async {
  try {
    val quote = quoteService.getQuote().await()
    response.write(quote)
  catch(_: Exception) {}
}
Is it just about the style of programming, or do coroutines offer something major over the other approaches? I see a few places that mention coroutines are non-blocking, but they don't seem to be, at least not in the same way that non-blocking io works. Can anyone help clarify this?
v

voddan

10/20/2017, 7:39 PM
In your example you have only one request and only one quote. But usually the logic is much more complicated. For example how would you implement a service that send back multiple quotes depending on the content of the request or the data in BD. In RX loops and ifs are hard. In coroutines they are just loops and conditions.
In other words, I suggest you try a messier example
u

uli

10/20/2017, 8:20 PM
The non-blocking calls and their succeeding callbacks are simply turned into a suspendable function which will release the thread it is running on while waiting for the callback
v

voddan

10/21/2017, 4:45 AM
Better performance, more throughput, etc,
Coroutines cover more use cases than RX, for example
yield
. I guess you could also get more performance if running coroutines in a single thread. Anyways what you call
style of coding
, and what I call
different abstraction
, is the main benefit of Coroutines, and all else are just bonuses.
2 Views