Wednesday, April 29, 2020

We were discussing Kotlin versus Java coroutines:


Coroutines are functions that enables asynchronous programming by launching and waiting for another code to execute. For example, we can make a request for a token and wait for it. This token can then be used to make a web-request for an item and process it. The processing can be done with threads.


the call to get a token can wait indefinitely in a blocking manner. When this occurs on numerous control threads, it hinders scalability. Instead this waiting can be avoided with a callback. the request for token is made asynchronous and the callback is invoked when done. Each of the methods such as getting a token, making a request to an item with the token and processing the item can now be asynchronous and involve a callback.


This benefit comes at the cost of exception handling within callbacks.  Instead Futures and Promises come to the rescue.  A future is an asynchronous call with a registered callback.  The Promise is the future result which in this case is the token.  When making a request for an item with the token in the form  of a future, the result of the post webrequest is returned immediately as a promise.


Promise avoids the nesting hell of callback by flattening and sequential logic. We can write requestTokenAsync().thenCompose { token -> createPostAsync(token, item) }.thenAccept { post -> processPost() }
This form composes and propagates exceptions with no nesting indentations but it introduces all those combinators in the form of thenSomething and thenSomethingElse ...
Kotlin coroutines rescues from this mode of programming by avoiding async and await and introducing a far simpler notion of suspend.
suspend fun requestToken(): Token {
       return token
}
And similarly,
suspend fun createPost(token: Token, item: Item): Post { … }
Fun processPost(post: Post) {…}
Suspend fun postItem(item: Item) {
      val token = requestToken()
      val post = createPost(token, item)
      processPost(post)
}
Exception handling and higher-order functions can continue to work like they did for regular functions
Even lambda’s can be suspended.





No comments:

Post a Comment