Kotlin Coroutines Beginner Example (Android)

Поділитися
Вставка
  • Опубліковано 29 вер 2024
  • High quality programming courses: codingwithmitc...
    In this video I take you through your first kotlin coroutines example.
    If you are complete beginner when it comes to coroutines and want to see what they're all about, this is the video for you.
    The main goal of coroutines is to "simplify asynchronous work by getting rid of callbacks." Coroutines are NOT threads. I like to think of coroutines as JOBS. And each "job" may contain "child jobs". Jobs that can run in any thread. Many coroutines can run in a single thread at once.
    They're kind of "like" threads because you can start them up and do work asynchronously, but they aren't threads. Many coroutines can exist and be running in a single thread.
    The main dispatchers for building coroutines is:
    1) Default (CPU intensive work)
    2) Main (UI Interactions)
    3) IO (Input/output. ex: network or disk transactions)
    Instagram: / codingwithmitch
    code: github.com/mit...

КОМЕНТАРІ • 330

  • @gilsonjuniorpro
    @gilsonjuniorpro 5 років тому +58

    Finally, an easy way to understand coroutines, thank you, helped me a lot

    • @codingwithmitch
      @codingwithmitch  5 років тому +1

      There's a lot more to it. This is a very very brief introduction

  • @codinginflow
    @codinginflow 5 років тому +70

    I don't like how you talk about AsyncTask and SQLiteOpenHelper

    • @codingwithmitch
      @codingwithmitch  5 років тому +54

      They're poop

    • @pembatamang8233
      @pembatamang8233 4 роки тому +4

      ​@@codingwithmitch yes they are 💩

    • @iamnvn
      @iamnvn 4 роки тому +5

      @@pembatamang8233 Also now the AsyncTask is deprecated.

    • @chibuikeoffu
      @chibuikeoffu 4 роки тому

      Someone is getting offended

    • @kunaljaiswal7119
      @kunaljaiswal7119 4 роки тому +4

      You both are so AWESOME :-)

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

    Corutines haveb been confusing to me until today. Thanks a lot.

  • @Fossor100
    @Fossor100 4 роки тому

    A much better explanation than on developer.android.com, where they included the ViewModel and distributed the code on multiple classes. Thanks!

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

      Anything by Google is always over-engineered and explained in the most opaque way possible!

  • @Pinipon.Selvagem
    @Pinipon.Selvagem 3 роки тому

    Thank you for the simple tutorial.
    Wanted to replace AsyncTask, since it is now deprecated, and this seems great! It will actually look better than the code i had.

  • @swissmatteo
    @swissmatteo 4 роки тому

    I absolutely loved your lesson on Coroutines. Thank you Mitch

  • @AhmedAli-jx9ie
    @AhmedAli-jx9ie 5 років тому +4

    thumbs up before watching the video

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

    Excellent video, very usefull, regards from Caracas, Venezuela

  • @SpectatorAlius
    @SpectatorAlius 3 роки тому

    "Coroutines are new" -- actually, Knuth was already writing about coroutines in the early 70s. They are covered in TAOCP. But for reason never made clear to me, Kotin coroutines use the same name, but have some important differences. The latter really are more like threads than Knuth's coroutines. The same can be said or Python's coroutines.
    In both Python and Kotlin, coroutines are spoken of in terms of 'call' and 'return/yield'. But Knuth did not do this: it was more like "don't use call at all, 'prime the pump 'by pushing the coroutine entry point you want and do RET!"

  • @JanM457
    @JanM457 3 роки тому +1

    Thanks for the great explanation!
    Simple, somewhat unrelated question that I am too dumb to google apparently: How are you setting the onClickListener for the button without linking the button through findViewById first? Am I missing something obvious?

  • @jackedroe
    @jackedroe 3 роки тому

    you deserve more then one like brother /b

  • @techmarinar
    @techmarinar 3 роки тому

    Hey man, thank you very much, this was very helpfull to me ♥️♥️

  • @asadansar6214
    @asadansar6214 3 роки тому

    Hi Mitch
    I have some doubt regarding threading, I hope you can help me to solve my problem.
    Let's assume I have two methods
    //following methods should run in separate thread at same time
    val students= getStedentList() // returns 1000 records //this method should run in IO thread
    val address= getStudentsAddress()// returns 1000 records //this method should run in IO thread
    //after getting all the students record and all the address , I have to add the data in a list with merging the students and address
    val studentDetails= emptyList()
    // we have to wait until all the data is fetching, but main Thread should not be blocked
    for ( i in 0..list.size){
    studentDetails.add(students[i].name,address[i].city)
    }
    Thanks in advance

  • @cosovic14
    @cosovic14 4 роки тому

    I have a question that my mentor asked me that I don't know how to answer...
    Since you can actually run regular functions inside of a corountine, what is the actual purpose of a suspend function? What's the point?
    for example if i have:
    fun test{
    Println("hello")
    }
    I can call this inside of a coroutine like so :
    launch {
    test()
    }
    So, what would be the point in putting suspend in front of my function name?

  • @shriduttkothari
    @shriduttkothari 4 роки тому

    Great explanation 👍

  • @devl0pr
    @devl0pr 4 роки тому

    We need more videos ! :)

  • @nivsaparov1
    @nivsaparov1 4 роки тому +1

    Thank you! Helped me a lot

  • @SatyamRaikwar262238
    @SatyamRaikwar262238 4 роки тому

    Want to see more.. thanks

  • @andreslauga
    @andreslauga 3 роки тому

    I loved it!!

  • @jagongirjahongir4835
    @jagongirjahongir4835 4 роки тому

    thanks a lot for this video

  • @irfanirawansukirman4809
    @irfanirawansukirman4809 5 років тому

    Hi bro. Thank you for this video. Next video, I think you should make a tutorial how implement it (real case maybe a movie app) using MVVM Architecture Component.

    • @codingwithmitch
      @codingwithmitch  5 років тому +1

      I'll prob do a bunch of simple coroutine stuff like this to show the basics. And right now I'm designing a course using MVVM/MVI with coroutines, Dagger, Kotlin, Retrofit, room, navigation components, etc.

    • @irfanirawansukirman4809
      @irfanirawansukirman4809 5 років тому

      @@codingwithmitch Nice 👍

  • @sooshil
    @sooshil 4 роки тому

    I almost copied your code... but the app didn't crash as expected in 15:31. It wait 1 second to to update the textview.
    weird...

  • @ArpitA5724
    @ArpitA5724 4 роки тому

    What is the max no of coroutines i should use in one thread?

  • @dhruvtatran5744
    @dhruvtatran5744 5 років тому +119

    Coroutines, another strong reason to shift from Java to Kotlin
    Thanks for the video

    • @codingwithmitch
      @codingwithmitch  5 років тому +3

      Yeah very strong. And this is just the surface of what it can do

    • @Sam-si7xv
      @Sam-si7xv 4 роки тому

      Hi, i think im late here, but i need to ask about your statement. So, java cant use coroutines?

    • @alexeymurnikov1413
      @alexeymurnikov1413 4 роки тому +1

      @@Sam-si7xv nope

    • @Monkeydluffy-we2fk
      @Monkeydluffy-we2fk 3 роки тому

      @nero I don't know y someone will use asynchronous task now instead of loaders or executors🙂

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

      @Saptarshi Samanta 1 year later, but yeah you can use kotlin with asynctask

  • @maXXik1337
    @maXXik1337 4 роки тому +9

    Me: Simple explanation? 23 minues? Naaah.
    Also me 23 minutes later: Well, good job.

  • @PaoloValerdi
    @PaoloValerdi 5 років тому +14

    Great! Next timer I think it's better to run the coroutines in the lifeCycleScope or scope one to the current activity/fragment or even better the viewModelScope :)

  • @kharagkunchok
    @kharagkunchok 3 роки тому +7

    I always findmy self landing in your channel when ever I searched any issue. Thanks

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

    Doesn't work. =(
    ---
    UPD:
    Need to declare
    lateinit var text: TextView
    lateinit var button: Button
    right after
    class MainActivity : AppCompatActivity()
    and then initialize them inside class MainActivity : AppCompatActivity()
    button = findViewById(R.id.button)
    text = findViewById(R.id.textView)
    class MainActivity : AppCompatActivity() {
    lateinit var text: TextView
    lateinit var button: Button
    var RESULT_1 = "result1"
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button = findViewById(R.id.button)
    text = findViewById(R.id.textView)
    button.setOnClickListener {
    CoroutineScope(IO).launch {
    fakeAPIRequest()
    }
    }
    }

  • @sudhir1274
    @sudhir1274 4 роки тому +6

    As a result of watching this video four times to fully understand the concepts of coroutines, I have successfully run a piece of code which for the past week kept crashing. This also works for normal Kotlin code outside of Android. Once again, thank you for sharing this video and explaining how coroutines work.

  • @ClintPaul89
    @ClintPaul89 4 роки тому +7

    Wow. This is like the simplest detailing someone can offer on Coroutines. I implemented it yesterday reading some other blog. I had my doubts still. Now it's all sorted. Thank you.

  • @DivyangM
    @DivyangM 3 роки тому +5

    A really good way to show an example and finally someone who actually knows the meaning of "beginners". Just recently started learning Kotlin and couldn't understand how coroutines work.
    This one is the best explanation possible for that, literally.
    Thanks a lot.

  • @leonardosibela
    @leonardosibela 3 роки тому +1

    Quick and interesting question:
    On 18:37 you say that withContext switch the context of the coroutine. Does it actually do that or it changes the coroutines itself?

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

    Nice explanation but small correction at 13:16 . Main, IO, Default these are the three co-routines dispatcher not scope.

  • @tanvimandanka2121
    @tanvimandanka2121 4 роки тому +10

    Just love the way he explains everything

  • @jesprotech
    @jesprotech 2 роки тому +3

    I really like this tutorial. Very easy to understand and it cleared up a lot of questions I had. 👍. It really puts in perspective the actual difference between coroutines and threads, which is so important when making reactive and resilient software applications.Thank you!

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

    Thanks for video before watching your video i found corutines a lot confusing

  • @anirudhyeddula3411
    @anirudhyeddula3411 5 років тому +4

    i've been reading several blogs and documentation, but this is just one video that made it look all so simple. thanks for the awesome video. Hope you keep churning out more of them.

  • @yasseraltamimi9060
    @yasseraltamimi9060 5 років тому +5

    I watched many tutorials and it was so confusing. your tutorial made it very easy and now I think I can start using it.
    Thanks a lot.

  • @macheeneraid1031
    @macheeneraid1031 4 роки тому +1

    currently using coroutine for my room CRUD while having MVP arch.
    I added coroutinScope().... inside my service, but in my view module(mainActivity), I didn't add the withContext().... but it didn't crash and is working fine.
    wondering why it didnt crash

  • @xenofonkarydis6406
    @xenofonkarydis6406 5 років тому +3

    Good Job Mitch...took you a long to switch to Kotlin and Coroutines. Enough with RxJava. :P :P

  • @dhrumitshah4387
    @dhrumitshah4387 4 роки тому

    Thanks Mitch for explanation. Could you please make videos on Coroutines channel and Flow? I see very few videos out there explaining these concepts.

  • @kodecoder
    @kodecoder 4 роки тому +1

    Hey Mitch, great tutorial, I have one doubt though,
    At 21:26 , the fakeAPIRequest function calls getResult1FromAPI which runs on the background thread, however, we are switching the context in setTextOnMainThread. Won't the getResult2FromApi be called on main because we did not switch the context back?

  • @amitozsingh5992
    @amitozsingh5992 5 років тому +4

    Please upload more on coroutines

  • @ramtin3760
    @ramtin3760 4 роки тому +1

    I really hate Kotlin Coroutines and prefer RxKotlin/Java (Reactive Programming), But this video does a good job of explaining and making it more interesting. I use Coroutines for Ktor only.

  • @karan548
    @karan548 5 років тому +4

    hey mitch please upload more examples of different cases of coroutines

    • @RameshK-dy6yb
      @RameshK-dy6yb 4 роки тому

      may refer ua-cam.com/video/x2QOzdh0Fqs/v-deo.html

  • @NomoBuddhay326
    @NomoBuddhay326 4 роки тому +1

    Superb Mitch, your way of explanation is too too... awesome in shot span of time with perfect example. Keep it up i watched all your lectures over android.

  • @kenargo
    @kenargo 4 роки тому +1

    I don't know if you mention it in another Coroutine presentation but there is one other difference between CoroutineScope() and withContext(). CoroutineScope() returns a job object withContext() returns the result of the suspend function. So where you would need to use job::invokeOnCompletion() in order to access results you would be able to direction access the result using withContext()

  • @quantass
    @quantass 3 роки тому

    Good job. Well explained easily better than any other source including the awful Kotlinlang.org site

  • @vikingcheng
    @vikingcheng 5 років тому +1

    this author is very good except that he uses fingers to point to people sometimes.

  • @amir123000
    @amir123000 3 роки тому +1

    I like the way that you explain ,whenever i got problem in android concept and implementation i check whether you put something about it on UA-cam or not. thank you very much

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

    Thanks, this has really been a nice lesson on coroutines. As this is my first encounter with kotlin and coroutines I am wondering what's the difference (sth. happening in the background) choosing IO or default...

  • @vinit.
    @vinit. 3 роки тому

    var result2 = getResult2FromApi(result1)
    The above line will execute on the Main thread as per your existing code.
    Because above to this line, you called setTextOnMainThread(result1).
    Which converted the Coroutine into Main and you not turned it to IO before calling this method.
    I am right?

  • @samirgawas
    @samirgawas 5 років тому +2

    Thanks Mitch...waiting for more videos...

  • @ngoquang2708
    @ngoquang2708 5 років тому +2

    Been waiting for this topic for so long. Now I am happy!

  • @rajatgupta-ld1wg
    @rajatgupta-ld1wg 3 роки тому

    Hi, I have a doubt. I am running this same code in my latest android+ kotlin versions and I can see it updates TextView if I put it in Any Scope.. like Main, IO, Default.. instead of throwing exception using UI in another thread.... Can anyone help me here?

  • @walkaboutneil
    @walkaboutneil 5 років тому

    Nice kick-starter Mitch. Good example to jump to coroutines for parallel work. Always helps to start with something solid.
    Here is good info on parallel: kotlinexpertise.com/kotlin-coroutines-concurrency/
    Thanks!

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

    Thanks for making this video. The task of making sequential requests based on network responses drives me crazy! Thanks for this excellent video. I really appreciate it.

  • @sayyedaamer9243
    @sayyedaamer9243 4 роки тому

    Hello Mitch, thanks for wonderful tutorials.
    I have a question, I am new to kotlin, I have noticed that the app size is big in kotlin as compared to java and the size of third party libraries for kotlin also big, as we know that app size is most important then why we use Kotlin, just to mke code less and easy? I am very confuse.
    Please answer.

  • @ignatiusn9851
    @ignatiusn9851 5 років тому

    Hey Mitch I got a request really not related to this video but rather one of your previous java/android video, theres this video you made about the 'single source of truth' in MVVM. can you pliz do this stuff in Kotlin plz I wanna know how to do that in Kotlin and youre the code artisan I know who is at home with these things. Thanks in advance

  • @baijusharma6027
    @baijusharma6027 5 років тому +3

    Thank you. Today, I learn new thing in Android.

  • @TransientBloke
    @TransientBloke 3 роки тому

    5:18 : The explanation of suspend keyword seems inaccurate.
    You said the suspend keyword means the function can be used in a coroutine, and if we remove suspend then you can't use it in a coroutine.
    I think it should be that, suspend means the function can ONLY be used in a coroutine, and if we remove suspend then it becomes a normal function, and can be called from anywhere (coroutine or not)

  • @avc8484
    @avc8484 4 роки тому

    Interestingly I tried to launch coroutines on default with button click, in a fragment. I did orientation change and used retaininstance (orientation change). But Coroutines dosen't launch after orientation change(it dosen't matter if i launched before orientation change). Can I know the reason? Mitch your tutorials are really helpful. Thanks

  • @David-yz9mb
    @David-yz9mb 4 роки тому

    So we are writing the year 2020 and still apps will crash because the IDE/compiler allows you to write UI changing code inside an async function.

  • @NimaAzh
    @NimaAzh 4 роки тому

    so simple and useful.tnx. but i did not get what the job is , I have read about it before but don't know what it does. is the coroutine same job concept ? I just know you said coroutine(suspend fun) is the job that is placed in thread.

  • @MrEEEE
    @MrEEEE 5 років тому +2

    Great job Mitch 😍

  • @maco7366
    @maco7366 4 роки тому

    I have a doubt. Is there any difference between the CoroutineScope(IO).launch{} and launch(IO){} ?

  • @martinsalcedoapps
    @martinsalcedoapps 4 роки тому

    Hello Mitch, How do you have the text variable binded by default to the xml object? I don't see the findViewById call.

  • @syedtayyabulmazhar6945
    @syedtayyabulmazhar6945 3 роки тому

    I was confused about 22:12 part. Like how does it _wait_ for result1 and then goes to result 2.
    So I looked in to _delay(time)_ method. What happens is that the delay method pauses the execution of the coroutine in which it is called for the given time, and then resumes it. Keep in mind that the coroutine is not a thread, which is why delay causes only the coroutine to pause and not the thread in which it is running.

  • @vijay6877
    @vijay6877 4 роки тому

    I'm getting error whenever I use coroutine. It force me to annotate my block of code with @InternalCoroutineApi I don't know why Google is not helping me either.

  • @harvindersidhu500
    @harvindersidhu500 3 роки тому

    Wow. Thanks Mitch. I think at this point Jetbrains and Google should probably just pay you.

  • @radosawjuszczyk638
    @radosawjuszczyk638 4 роки тому

    Click the button, leave the app before 1s, enjoy the crash. You should cancel this job when activity is destroyed.

  • @asadansar6214
    @asadansar6214 3 роки тому

    If anyone has the idea regarding this problem, he can reply. (Please don't use infinite loop with some boolean flag to wait in IO thread)

  • @dibyendusamanta4540
    @dibyendusamanta4540 4 роки тому

    How Update UI when coroutines get any exception and will the next supend function work if any exception occur on firstAPI call ?

  • @David-yz9mb
    @David-yz9mb 4 роки тому

    Wouldn't it be more simplier if you wouln't need to write "suspend", why does kotlin requires this at all? why not guessing it by itself?

  • @Codetutor-DemystifyCoding
    @Codetutor-DemystifyCoding 5 років тому

    Any Android developer worth his/her salt will really appreciate coroutines. This is going to make our life much more enjoyable as Android developer.

  • @tubeyoukonto
    @tubeyoukonto 3 роки тому

    All nice and good, but why do that and not just open a thread and then use 'runOnUiThread' to do whatever it is you wanted to do on the UI thread? I understand how coroutines function, but didnt yet understand their purpose.

  • @paschalismp
    @paschalismp 3 роки тому

    7:52 I hope Kotlin will give as something like `__FUNCTION__` for this!

  • @powerlevel8000
    @powerlevel8000 3 роки тому +1

    I'm now super excited to browse through all your content, you kept it really simple and explained the concept quite well, thank you! And subscribed.

  • @dasstraat
    @dasstraat 3 роки тому

    Nice example, now I can continue the Kotlin Adventure... C++ is still easier with threads

  • @jatinvashisht4293
    @jatinvashisht4293 3 роки тому

    For me learning android concepts means two channels:
    1. Coding with Mitch
    2. Coding in Flow

  • @ShivaPrasad-hm5lk
    @ShivaPrasad-hm5lk Рік тому

    I did one such thing where I made a request to random word api and then after result comes another api is called for meaning of it but not spontaneously only when user wants to

  • @ivanbartolelli9361
    @ivanbartolelli9361 3 роки тому +1

    I've understood everything. This is an excellent video!

  • @nabeeltech7885
    @nabeeltech7885 3 роки тому

    People say I sound like Mitch though I'm Pakistani . Maybe my English is good

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

    Your way of explaining things is very unique, RESPECT.

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

    i was stuck with an App that i had to use an API requests, you've saved me thank you

  • @jackdanyal4329
    @jackdanyal4329 4 роки тому

    why coroutines not in language core? why we should import it with maven or gradle? so shame.

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

    Thank you for the Video.. You made Coroutine as easy as easy to understand for a beginner.!!!

  • @krishnakumarmishra6583
    @krishnakumarmishra6583 4 роки тому

    I did not get any crash when I directly updated textView from IO dispatcher .

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

    "private suspend fun" sounds like something a drill sergeant would say.

  • @gilong1311
    @gilong1311 3 роки тому +1

    Hey Mitch, just tried it myself. Great tutorial, it cleared up my understanding of suspend functions. I was under the impression that delay() would suspend each suspend function and not the entire coroutine. Thanks for clearing that up!

  • @abdulsametklncarslan7492
    @abdulsametklncarslan7492 3 роки тому

    Should I use coroutines when I read data from Firebase Database or Storage as a background thread?

  • @ashwaniyadav3661
    @ashwaniyadav3661 4 роки тому

    i didn't knew about Room Persistence Library.... am i the only one?

  • @fatemacherif5069
    @fatemacherif5069 5 років тому +2

    Thank you so much for this video, Helped a beginner like me a lot!

  • @yasmeenemam
    @yasmeenemam 3 роки тому

    Thanks a lot this is the most clear and obvious explanation for Coroutines.

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

    i feel like im late to the party, but hey, this intro was really good! Thanks!

  • @daoanhvu4129
    @daoanhvu4129 3 роки тому

    Thank you, I have gotten confused about coroutines until I find this video.

  • @ahaha233
    @ahaha233 5 років тому +1

    You're the best Android teacher. Thanks so much for your videos.

  • @silver350z94
    @silver350z94 4 роки тому +1

    Thanks Magneto

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

    Explained with a very detailed description. Thanks for the video

  • @bellaarorathelabradorretre9031
    @bellaarorathelabradorretre9031 4 роки тому

    Dear Mitch ,can you please teach us delegation and delegated properties in kotlin?