Tuesday, April 28, 2020

Kotlin versus Java continued:

We were discussing Kotlin versus Java. Kotlin brings a ton of new features over Java such as Lambda expressions, extension functions, smart casts, String templates, primary constructors, first-class delegation, type inferences, singletons, range expressions, operator overloading, companion objects and coroutines. 

We now discuss 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
}

#codingexercise
List <String> mapByLookupHostname(List <String> resources) { 
Return resources.stream () 
             . map( x ->getHostname(x)) 
              .collect (Collectors.toList ()); 

} 

No comments:

Post a Comment