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...
Finally, an easy way to understand coroutines, thank you, helped me a lot
There's a lot more to it. This is a very very brief introduction
I don't like how you talk about AsyncTask and SQLiteOpenHelper
They're poop
@@codingwithmitch yes they are 💩
@@pembatamang8233 Also now the AsyncTask is deprecated.
Someone is getting offended
You both are so AWESOME :-)
Corutines haveb been confusing to me until today. Thanks a lot.
A much better explanation than on developer.android.com, where they included the ViewModel and distributed the code on multiple classes. Thanks!
Anything by Google is always over-engineered and explained in the most opaque way possible!
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.
I absolutely loved your lesson on Coroutines. Thank you Mitch
thumbs up before watching the video
Excellent video, very usefull, regards from Caracas, Venezuela
"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!"
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?
you deserve more then one like brother /b
Hey man, thank you very much, this was very helpfull to me ♥️♥️
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
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?
Great explanation 👍
We need more videos ! :)
Thank you! Helped me a lot
Want to see more.. thanks
I loved it!!
thanks a lot for this video
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.
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.
@@codingwithmitch Nice 👍
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...
What is the max no of coroutines i should use in one thread?
Coroutines, another strong reason to shift from Java to Kotlin
Thanks for the video
Yeah very strong. And this is just the surface of what it can do
Hi, i think im late here, but i need to ask about your statement. So, java cant use coroutines?
@@Sam-si7xv nope
@nero I don't know y someone will use asynchronous task now instead of loaders or executors🙂
@Saptarshi Samanta 1 year later, but yeah you can use kotlin with asynctask
Me: Simple explanation? 23 minues? Naaah.
Also me 23 minutes later: Well, good job.
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 :)
I always findmy self landing in your channel when ever I searched any issue. Thanks
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()
}
}
}
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.
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.
no problem brother
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.
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?
Nice explanation but small correction at 13:16 . Main, IO, Default these are the three co-routines dispatcher not scope.
Just love the way he explains everything
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!
Thanks for video before watching your video i found corutines a lot confusing
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.
Always churning brother
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.
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
Good Job Mitch...took you a long to switch to Kotlin and Coroutines. Enough with RxJava. :P :P
yep. Time to make the switch.
You can still use rxkotlin as well.
Thanks Mitch for explanation. Could you please make videos on Coroutines channel and Flow? I see very few videos out there explaining these concepts.
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?
Please upload more on coroutines
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.
hey mitch please upload more examples of different cases of coroutines
may refer ua-cam.com/video/x2QOzdh0Fqs/v-deo.html
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.
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()
Good job. Well explained easily better than any other source including the awful Kotlinlang.org site
this author is very good except that he uses fingers to point to people sometimes.
Wut
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
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...
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?
Thanks Mitch...waiting for more videos...
Been waiting for this topic for so long. Now I am happy!
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?
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!
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.
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.
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
Thank you. Today, I learn new thing in Android.
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)
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
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.
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.
Great job Mitch 😍
I have a doubt. Is there any difference between the CoroutineScope(IO).launch{} and launch(IO){} ?
Hello Mitch, How do you have the text variable binded by default to the xml object? I don't see the findViewById call.
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.
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.
Wow. Thanks Mitch. I think at this point Jetbrains and Google should probably just pay you.
Click the button, leave the app before 1s, enjoy the crash. You should cancel this job when activity is destroyed.
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)
How Update UI when coroutines get any exception and will the next supend function work if any exception occur on firstAPI call ?
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?
Any Android developer worth his/her salt will really appreciate coroutines. This is going to make our life much more enjoyable as Android developer.
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.
7:52 I hope Kotlin will give as something like `__FUNCTION__` for this!
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.
Nice example, now I can continue the Kotlin Adventure... C++ is still easier with threads
For me learning android concepts means two channels:
1. Coding with Mitch
2. Coding in Flow
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
I've understood everything. This is an excellent video!
People say I sound like Mitch though I'm Pakistani . Maybe my English is good
Your way of explaining things is very unique, RESPECT.
i was stuck with an App that i had to use an API requests, you've saved me thank you
why coroutines not in language core? why we should import it with maven or gradle? so shame.
Thank you for the Video.. You made Coroutine as easy as easy to understand for a beginner.!!!
I did not get any crash when I directly updated textView from IO dispatcher .
"private suspend fun" sounds like something a drill sergeant would say.
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!
Should I use coroutines when I read data from Firebase Database or Storage as a background thread?
i didn't knew about Room Persistence Library.... am i the only one?
Thank you so much for this video, Helped a beginner like me a lot!
Thanks a lot this is the most clear and obvious explanation for Coroutines.
i feel like im late to the party, but hey, this intro was really good! Thanks!
Thank you, I have gotten confused about coroutines until I find this video.
You're the best Android teacher. Thanks so much for your videos.
Thanks Magneto
Explained with a very detailed description. Thanks for the video
Dear Mitch ,can you please teach us delegation and delegated properties in kotlin?