Git Product home page Git Product logo

kotlincoroutinepractice's Introduction

Basic Coroutine Notepoint:

======Thread and Coroutine========

  1. We don’t perform long running task on Main thread as it is UI thread. We used to do long running operations on background threads. This is not a recommended solution as we end up with many background threads in app. Threads are expensive. We might get OutOfMemoryError.
  2. We create coroutines for each long running operations. We can create as many as coroutines in a single thread. They are very cheap. We make use of thread efficiently.
  3. Application waits for thread to complete its operation whereas Application doesn’t wait for Coroutine to complete its operation.

======Coroutine and its builders========

Screenshot 2023-03-07 at 9 50 29 PM

  1. Coroutine builders are use for creating coroutine. There are 3 ways to create coroutine: launch, async , runBlocking
  2. Similarity in launch and async is they create coroutine that doesn’t block thread.
  3. runBlocking create coroutine that block thread. It is use when we need to call suspend function from main thread and while testing suspend function.
  4. Always remember two things regarding coroutine, thread on which it is executing and coroutineScope
  5. launch and async inherits parent coroutine thread and coroutineScope
  6. runBlocking creates coroutine on caller thread.
  7. When we use GlobalScope with launch/async for creating coroutine then our coroutine will have global scope means App level. This is the easiest way to launch coroutine but only use when needed.
  8. GlobalScope we can use for long running operation that doesn’t bounded to particular screen. example, multiple images sharing on WhatsApp. User should able to navigate any screen in WhatsApp.
  9. launch is fire and forgot . It returns job for controlling coroutine but doesn’t have return value from block
  10. Async returns Deferred job that has value.
  11. runBlocking doesn’t returns Job. It returns last line value in block

======Coroutine Cancellation===

  1. We can cancel coroutine if its cooperative. Cooperative means suspending functions that are in kotlin.coroutine package.
  2. For cancelling non-cooperative coroutine, we can use ensureActive() or yield().

Screenshot 2023-03-07 at 10 18 21 PM

  1. If we cancel, cancellable coroutine then cooperative suspend function throws CancellationException
  2. We can not run suspend function from finally block, because Coroutine running this code is already cancelled. Still if we want to run suspend function in finally block then wrap the code within withContext(NonCancellable) function
  3. withContext() is used for changing coroutine context. it makes main safe suspend function.
  4. withTimeout() and withTimeoutNull() are also coroutine builder. Both usages for time bounded coroutine operation. Both return lambda result. withTimeout() throws TimeoutCancellationException on timeout.

========== Unit testing coroutines =================
USE CASE 1: For testing suspend function
Screenshot 2023-03-07 at 10 23 50 PM Screenshot 2023-03-07 at 10 24 57 PM

USE CASE 2: For testing a function that trigger a coroutine
Screenshot 2023-03-07 at 10 26 13 PM Screenshot 2023-03-07 at 10 27 57 PM

USE CASE 3: For testing a set of instruction before triggering a coroutine.
for testing //Do something else in below image Screenshot 2023-03-07 at 10 29 38 PM Screenshot 2023-03-07 at 10 33 38 PM

=======Composing Suspending functions(series, parallel and lazy)=================

  1. By defaults, Coroutine works in sequentially.
  2. For concurrent execution, create child coroutines for all our tasks.we can use async and launch
  3. start = CoroutineStart.LAZY with async coroutine builder

=======Dispatchers, CoroutineContext and CoroutineScope================

  1. Types of Coroutines: BlockingCoroutine, StandAloneCoroutine and DefferedCoroutine. These types come to know from CoroutineScope
  2. CoroutineContext elements: Dispatchers(It decides threads), CoroutineName and Job

==========Thumb Rule for using Coroutine===============

  1. Use 'withContext' when you do not need the parallel execution
  2. Use 'async' only when you need the parallel execution
  3. Both 'withContext' and 'async' can be used to get the result which is not possible with 'launch'
  4. Use 'withContext' to return the result of a single task
  5. Use 'async' for results from multiple tasks that run in parallel

==========Coroutine notepoint from kotlin coroutine playlist in android developers youtube channel===============

  1. What problem does coroutine solve?
    Ans: It simplify asynchronous programing. we dont need to write callback. kotlin internally writes callback.
  2. What is coroutine?
    Ans: Runnable with superpowers. it takes a block of code and run it on a perticular thread. other perks like cancellation and exception handling. Cancellation and exception handling are very difficult in other versions of asynchronous programing, for example callback.
  3. What is main safe function?
    Ans: suspend function that take responsibility for switching the thread. it doesn't rely on caller side. use withContext() for changing thread.

Screenshot 2023-03-07 at 9 18 51 PM

4. What types of dispatchers in coroutine?
Ans:

Screenshot 2023-03-07 at 9 23 24 PM

===============Good coroutine articles references======= Screenshot 2023-03-07 at 10 38 35 PM

  1. Coroutines internal working part 1 - shared by Atul Kumar. best video.
  2. Coroutines internal working part 2 - shared by Atul Kumar. best video.
  3. Coroutines under the hood - Kt Academy
  4. How does suspension work in Kotlin coroutines? - Kt Academy
  5. Suspend function under the hood simple article - shared by Athul Antony
  6. Flow, StateFlow, shared flow testing emitting and collecting side - coding with mohit. After 2 days struggle, finally found.
  7. Kotlin coroutine Use cases example - LukasLechnerDev GitHub
  8. Kotlin coroutine- medium article by Magda Miu
  9. Android developer medium- Neeraj shared
  10. Android developer medium- Neeraj shared
  11. Roman - Neeraj shared
  12. Asynchronous programming - beautiful blog by bmc. general concept.

Find this project useful?:heart:

  • Support it by clicking the ⭐ button on the upper right of this page. ✌️

kotlincoroutinepractice's People

Contributors

sagarkisanavhad avatar

Stargazers

 avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.