In-Depth Guide to Coroutine Cancellation & Exception Handling - Android Studio Tutorial

Поділитися
Вставка
  • Опубліковано 6 жов 2024
  • With Kotlin's coroutines, we have an amazing framework to perform async operations. However, it's not as easy as it first seems. Cancellation and exception handling make coroutines a tricky topic. This video clarifies what you need to know.
    ⭐ Get certificates for your future job
    ⭐ Save countless hours of time
    ⭐ 100% money back guarantee for 30 days
    ⭐ Become a professional Android developer now:
    pl-coding.com/...
    Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/...
    Join this channel to get access to perks:
    / @philipplackner
    Join my Discord server:
    / discord
    Regular programming advice on my Instagram page: / _philipplackner_
    Checkout my GitHub: github.com/phi...
    You like my free content? Here you can buy me a coffee:
    www.buymeacoff...

КОМЕНТАРІ • 94

  • @it5454
    @it5454 2 роки тому +43

    Man, this is just so awesome = do you even imagine how much time you save for all the developers who watch your videos? Dozens, possibly hundreds and thousands of lifetimes if we sum up all of it = thank you, sir! In my humble opinion, people like you deserve all the millions of dollars you'll get.

    • @PhilippLackner
      @PhilippLackner  2 роки тому +8

      Thank you so much for these kind words 🙏

  • @pepep5840
    @pepep5840 4 місяці тому +2

    I can't thank you enough for this fantastic tutorial on coroutine cancellation and exception handling in Android Studio. Your clear explanations and detailed examples helped me solve a stubborn bug that had been plaguing my project for days. Your in-depth guide was exactly what I needed to understand how to properly manage coroutine lifecycles and handle exceptions efficiently. This video is a must-watch for anyone working with Kotlin coroutines. Keep up the great work!

  • @AmitGupta-pz9xd
    @AmitGupta-pz9xd 2 роки тому +12

    You are an exceptional Teacher. This is quite an advanced topic which you have explained so easily. May you have all the health and Wealth in your life! Keep going !

  • @SaherAlSous-welcomes-you
    @SaherAlSous-welcomes-you 2 роки тому +12

    Hey Philip... this is really useful... you can add also that generally. the coroutines should be "Cooperative" with cancellation, meaning that you can check if the job is still active before entering the coroutine code, if you cancel it at any point, and there is no delay or status check, then the coroutine will continue, (delay check for the job status when it finishes).

  • @Alchemist10241
    @Alchemist10241 2 роки тому +9

    You have covered almost all of the extremely important edge cases of coroutines exception handling. Great Job. ✈

  • @ericwathome783
    @ericwathome783 2 роки тому +2

    Dude. You provide so much value. I hope you know that. You make Android so easy to understand and I believe a lot of people are grateful for that. Am watching all the way from Kenya. Kindly give a shout-out in one of your videos if it's okay with you. Am a huge fan

  • @sopecoto
    @sopecoto Рік тому +2

    wow, i just wanna say thank you very much for this video - too short but very simple and efficent way to understand all of them

  • @victormedeiros4538
    @victormedeiros4538 2 роки тому +1

    This is going to help me a lot!!! I'm facing exactly this problem of error handling in coroutine scopes in my job. Very good video, thanks!!!

  • @shootsir
    @shootsir Рік тому +2

    First of all thank you for the video. You definitely help me to clear some of my confusions. But I would like to know how did you learn all this stuff? What materials have you read and etc? It's always good to have a teacher like you but knowing how you learn would be so much more beneficial. Thanks

  • @SreejiM
    @SreejiM 2 роки тому +2

    Thank you very very much for such an AMAZINGLY INFORMATIVE VIDEO 🙏🙏🙏
    Normally, it would take WEEKS to UNDERSTAND such an ADVANCE CONCEPT, but this VIDEO explains all those PRACTICALITIES in such a DETAILED MANNER. 👏👏👏
    Thanks once again for helping us all GROW with such WONDERFUL VIDEOS 😇😇😇

  • @mehulbisht9708
    @mehulbisht9708 2 роки тому +1

    21:13 Reminded me of Gabor (Zhuinden) mentioning in Florian's podcasts about third-party libraries not propagating the cancellation exceptions up the hierarchy properly and why coroutine cancellation is so complicated than what it seems.

  • @GabrielTrifa
    @GabrielTrifa 8 місяців тому

    just went through the whole serie of coroutines. your content is awesome!!

  • @vengateshm2122
    @vengateshm2122 2 роки тому

    That's why Philip is there to teach us about all the unknowns and nuances.

  • @gargyash
    @gargyash 2 роки тому +1

    Thank you so much for this video. I was recently learning about coroutines and this will help alot!

  • @miladhashemzadeh5626
    @miladhashemzadeh5626 2 роки тому +1

    Most of the times it be comes so painful to handle errors of multiple flows thank you bro.

  • @ChrisAthanas
    @ChrisAthanas 2 роки тому +2

    This is the best explanation of a VERY POORLY documented topic. Thank you very much!

  • @nijuyonkadesu
    @nijuyonkadesu Рік тому

    crisp content 💕 thanks to you ! I'm now confident to work with coroutines !!

  • @ihsanulhaq89
    @ihsanulhaq89 2 роки тому

    you are a life saver bro! thanks for a detailed overview of coroutines!

  • @surajmaity6194
    @surajmaity6194 Рік тому

    Your teaching is really good ..
    Thanks a lot

  • @johanofcourse
    @johanofcourse Рік тому

    Thank you Philipp, you explained this topic very well!

  • @berkc5323
    @berkc5323 2 роки тому +2

    Which theme of android studio are you using? I really enjoy watching your videos, thanks for sharing this kind of detailed knowledge.

  • @jmorasot
    @jmorasot 2 роки тому

    Awesome video like all others. I always learn something new watching you.

  • @chonnikansipan80
    @chonnikansipan80 2 роки тому

    clicked on. Very detailed and to the point, thank you so much for tNice tutorials! I subscribed and I look forward to watcNice tutorialng and learning more about

  • @princeneo294
    @princeneo294 Рік тому

    This is just awesome, thanks Philipp

  • @sakura61223
    @sakura61223 2 роки тому +1

    good lessons,helps me clarify coroutines a lot man 👌👌

  • @Alchemist10241
    @Alchemist10241 6 місяців тому

    Florina Muntenescu & Manuel Vivo video and explanations about coroutine exception handling was bs, but Philipps' is very easy to understand and implement, some people are born to do the job in the best way possible but others are here just to waste our time

  • @hamedhardani8302
    @hamedhardani8302 2 роки тому

    Thanks Philipp. It was really helpful 🤝

  • @NiMa-1629
    @NiMa-1629 2 роки тому

    Nice 😊 another amazing video. I will watch it as soon as possible.

  • @EnelAlmonte
    @EnelAlmonte 2 роки тому

    You are doing a excellent Job!

  • @nipunshah1373
    @nipunshah1373 2 роки тому

    Splendid Explanation !

  • @mattshoemaker386
    @mattshoemaker386 11 місяців тому

    Using try/catch is essential if you want to recover from the exception and continue the coroutine. If you propagate to an exception handler, then your coroutine is dead and unrecoverable.

    • @mattshoemaker386
      @mattshoemaker386 11 місяців тому

      As long as you're careful to call ensureActive() in your catch block

  • @flowzk921
    @flowzk921 Рік тому

    very insightful video, thank you!

  • @alihosseinnezhad2957
    @alihosseinnezhad2957 2 роки тому

    Thank you philipp,
    That was very helpfull 😊

  • @raghavendpai
    @raghavendpai 2 роки тому

    Awesome explanation...Thanks👍

  • @ishantsharma16
    @ishantsharma16 2 роки тому

    Hii @ phillip . Please add deep video on Coroutine what is invoke function how can we use with examples

  • @AmirRaza1
    @AmirRaza1 2 роки тому

    Would you please make a video on Structured Concurrency?

  • @robertorebolos8861
    @robertorebolos8861 2 роки тому

    Thanks bro you helped me so much.

  • @UpLiftingU007
    @UpLiftingU007 2 роки тому +1

    F**k bro watched this video at night and in my morning interview I answered 2 more questions 😀

  • @homamhomam1879
    @homamhomam1879 Рік тому

    Great work man keep going :)

  • @suapccolangelo
    @suapccolangelo 2 роки тому

    Amazing video, thank you!

  • @sumitkumardhule1082
    @sumitkumardhule1082 2 роки тому

    Great explanation !!

  • @SpaceGuideHub
    @SpaceGuideHub Рік тому +1

    You look like a British, but you have a such strange accent, that I don't understand where are you from. Your lessons are good. Thanks!

  • @arsooamgad
    @arsooamgad 2 роки тому

    Best one has posted a new video

  • @PrajwalCanonShutter
    @PrajwalCanonShutter Рік тому

    It seems like u single handedly built the co-routines toolkit, did u ?

  • @o.z.sidd.
    @o.z.sidd. Рік тому

    bro loved it

  • @salihuumar3138
    @salihuumar3138 Рік тому

    Wonderful, Thanks

  • @wizardy6267
    @wizardy6267 2 роки тому

    Very nice tutorial, thanks. One question is: in a complex code base, is there a good way to check a coroutine scope is a root coroutine scope? The reason I ask because when I watched the video first time, the exception propagation is a bit confuse, since an exception can be propagate to its parent coroutine. Then I got confuse why the `lifecycleCoroutine` not able to catch the exception from its child coroutine. Until I read the kotlin doc saying the `root` coroutines`treat exceptions as uncaught exceptions`. I guess that requires some java background to understand the concept easily.

  • @safionweb
    @safionweb 2 роки тому

    Amazing job!

  • @abhimveer7873
    @abhimveer7873 2 роки тому

    Super useful 🤩

  • @shivamdawar97
    @shivamdawar97 Рік тому

    Its so amazing.

  • @ViniciusOliveira-yd5ew
    @ViniciusOliveira-yd5ew 2 роки тому

    Amazing video

  • @mustafaammar551
    @mustafaammar551 2 роки тому

    you are the best
    thank you

  • @tibrec8
    @tibrec8 2 роки тому

    well played :D Keep content up

  • @manusarangal449
    @manusarangal449 7 місяців тому

    Hi Philipp, Great video!
    Quick question: You mentioned that the exception is propagated up the launch tree. If that's the case, the following code shouldn't crash as the parent launch is handling the exception:
    launch {
    try {
    launch {// Child 1
    delay(500)
    throw Exception("error")
    }
    } catch (e: Exception) {
    Log.d("TestDrake", "Exception caught")
    }
    }
    However, It does crash - the parent launch does not catch the exception propagated by the child coroutine. Could you please explain?

    • @PhilippLackner
      @PhilippLackner  7 місяців тому

      You can't catch them that way, you need a coroutine exception handler and then it should work

    • @manusarangal449
      @manusarangal449 7 місяців тому

      ​@@PhilippLackner I see. Then what does it mean by the exception being propagated up the launch tree if it can't be caught by a parent coroutine? Thanks!

  • @dylangrijalva944
    @dylangrijalva944 2 роки тому

    Excellente explanation! Btw: What font do you use?

  • @MrBicelis
    @MrBicelis 2 роки тому

    At 1:17 you moved the "launch" block up and into the "try" block. What's the keyboard shortcut for that? :)

    • @FlorianMeyer1983
      @FlorianMeyer1983 2 роки тому

      On Windows it is usually Ctrl + Shift + Up. In Android Studio, if you go to File -> Settings -> Keymap, you can search for "Move Statement Up" to find this one. It works similar to "Move Line Up", but moves a whole statement. This also works nice of whole functions to clean up the order of your class functions (for example...)

  • @hossamqandel5638
    @hossamqandel5638 2 роки тому

    hi Philipp
    could u make firestore Chat app?

  • @akarshmittal9601
    @akarshmittal9601 Рік тому

    lifecycleScope.async {
    val result = async {
    delay(500L)
    throw Exception("error")
    "result"
    }
    val strResult = result.await()
    }
    why this does not throw exception

  • @neoplaygame
    @neoplaygame 2 роки тому

    Hi Philip, I just have one minor question about the scope cancellation. I see people using return@launch. is there any different between return@launch and cancel() ?

  • @montuedge
    @montuedge 7 місяців тому

    14:00 Point !!!

  • @AnanthAvinash
    @AnanthAvinash 10 місяців тому

    can you tell me the reason of app crash. i tried based on your content
    1.this will crash app
    val scope= CoroutineScope(Job())
    scope.launch {
    val c=async {
    throw Exception("exception B2 2")
    }
    launch {
    try {
    c.await()
    }catch (e:Exception){}
    }
    }
    2.this will not
    val scope= CoroutineScope(Job())
    scope.launch {
    val c=scope.async {
    throw Exception("exception B2 2")
    }
    launch {
    try {
    c.await()
    }catch (e:Exception){}
    }
    }
    *difference: inner async coroutine launched by using scope again.

  • @McRookworst
    @McRookworst 2 роки тому

    How do you get those coloured lines in logcat?

  • @bhagarenikhil
    @bhagarenikhil 2 роки тому

    @Philipp Lackner 3:25 per my understanding outer coroutine (line no 20 in code) is already handling the exception in try catch block then app should not be crashed. Right?
    Pleas let me know if I missing anything. Thank you

    • @PhilippLackner
      @PhilippLackner  2 роки тому

      Nah, that's exactly what I mentioned at the beginning how it seems intuitive, but that's not how it works 😁

  • @khapp7821
    @khapp7821 2 роки тому

    please make video with some louder volume.

  • @domonk7450
    @domonk7450 2 роки тому

    is putting a coroutine inside another coroutine common practice?

  • @hanswurschtms
    @hanswurschtms 2 роки тому

    Sag mal, warst du auf der Droidcon Berlin 22?

    • @PhilippLackner
      @PhilippLackner  2 роки тому

      ja, sogar als speaker

    • @hanswurschtms
      @hanswurschtms 2 роки тому

      @@PhilippLackner nice. Welchen Talk? Mist, da saß ich wohl woanders. Gute Sache :)!

    • @yodgorbekkomilov3383
      @yodgorbekkomilov3383 2 роки тому

      @@PhilippLackner please make tutorial jetpack compose exoplayer music app with leanback library thanks beforehand for your answer

    • @PhilippLackner
      @PhilippLackner  2 роки тому

      @@hanswurschtms 5 common traps you can step into when using coroutines 😄

  • @Akshaykumar-xr9yj
    @Akshaykumar-xr9yj 2 роки тому

    When i run infinite loop in coroutine, then even after scoped canclled the loop keeps printing value in logcat. It only stops when i close app from recent apps. Is it default behaviour of coroutine scope.

    • @PhilippLackner
      @PhilippLackner  2 роки тому

      Run the loop like this and it won't happen anymore:
      while(isActive) {
      ...
      }
      You need to actively check for cancellation in a coroutine. Cancellation is cooperative

    • @Akshaykumar-xr9yj
      @Akshaykumar-xr9yj 2 роки тому

      @@PhilippLackner Thank you very much. It really helped me

  • @sarvarxyz
    @sarvarxyz 8 місяців тому

    Duhh... coroutines are so confusing

  • @xalikv
    @xalikv 2 роки тому

    ......................

  • @mdjahidulislam9205
    @mdjahidulislam9205 2 роки тому

    Hi
    kotlinx.coroutines.JobCancellationException: UndispatchedCoroutine was cancelled
    getting this issue when i change activity(it was observing a stateflow from ViewModel )