Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Bottom Up View of Coroutines

Bottom Up View of Coroutines

Basics of Coroutines

Rooparsh Kalia

January 19, 2021
Tweet

Other Decks in Technology

Transcript

  1. Callback Hell A callback is a function that will be

    executed after another function has finished executing. And if there are a series of things to be done synchronously then we will fall into callback hell that can lead us to ambiguity in understanding the code. It depends on the number of steps and logic we have in our applications
  2. RxJava/RxKotlin We can also opt for RxX stack from Reactive

    world, but that mean we are required to add another tool in our knowledge domain as well as our project.
  3. Some issues with Rx : 1. Learning curve 2. Project

    level structural changes 3. Dependency on 3rd Party.
  4. What are Coroutines? Coroutines are nothing but light-weight threads. Coroutines

    provide us an easy way to do synchronous and asynchronous programming.
  5. From Official docs, “One can think of a coroutine as

    a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine.”
  6. 1. Dispatchers 2. CoroutineContext 3. Job 4. CoroutineScope Determines what

    thread or threads the corresponding coroutine uses for its execution. The coroutine dispatcher can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined.
  7. 1. Dispatchers 2. CoroutineContext 3. Job 4. CoroutineScope Coroutines always

    execute in some context represented by a value of the CoroutineContext type, defined in the Kotlin standard library.
  8. Coroutine Context A coroutine context is an indexed set of

    elements that define the behaviour of a Coroutine.
  9. Some Use cases of Coroutine: 1. Parallel/Series Network Call 2.

    Handling Exceptions 3. Managing Thread for Disk operations
  10. Difference between launch and async The difference is that launch

    returns a Job and does not carry any resulting value, while async returns a Deferred -- a light-weight non-blocking future that represents a promise to provide a result later. So async starts a background thread, does something, and returns a token immediately as Deferred .
  11. QnA Time Any questions ?? Feel free to drop any

    queries and follow me at @i_am_rooparsh