No video

95% Don't Understand THIS About Coroutines (Main-Safety)

  Рет қаралды 27,697

Philipp Lackner

Philipp Lackner

Күн бұрын

In this video, you'll learn about main-safety, what this means and why it's important to ensure a fluent app experience.
💻 Let me be your mentor and become an industry-ready Android developer in 10 weeks:
pl-coding.com/...
⭐ Courses with real-life practices
⭐ Save countless hours of time
⭐ 100% money back guarantee for 30 days
⭐ Become a professional Android developer now:
pl-coding.com/...
Get my FREE PDF about 20 things you should never do in Jetpack Compose:
pl-coding.com/...
Regular programming advice on my Instagram page:
/ _philipplackner_
Join my Discord server:
/ discord

Пікірлер: 80
@scottloewke5199
@scottloewke5199 6 ай бұрын
The rule Philipp refers to is a convention only. It states that a suspend function should never block the calling thread. If we write the suspend function, then the responsibility is ours to ensure that it is main-safe. If we use a 3rd-party suspend function, then it's the responsibility of that developer to abide by the convention. However, it is still our responsibility to ensure (e.g., read the documentation or study the code) that the 3rd-party suspend function follows the convention. In the case of both Retrofit and Room, their documentation states that any suspend functions they generate will be main-safe.
@bitwisedevs469
@bitwisedevs469 10 ай бұрын
Always setting the Dispatcher even though we shouldn't is a code smell. Thanks for awesome content
@juanherrera9521
@juanherrera9521 Ай бұрын
withContext just means that everything inside its lambda will be executed in the specified dispatcher, it does no mean that it will magically make the functions called inside of it non-blocking, but it is useful because we can offload the main thread from heavy operations (like an http call or a filesystem operation) and just block a thread on the IO dispatcher instead and then get the result on the calling thread (Main in this case), so it is basically a callback but without the ugliness of it
@hamedborna7037
@hamedborna7037 9 ай бұрын
Thanks Philipp it was very useful. to me you're the most trustworthy person I've ever seen. I can always rely on your content🤘🏻
@PhilippLackner
@PhilippLackner 9 ай бұрын
Thanks a lot, that's a big compliment 🙏
@bidbid5413
@bidbid5413 10 ай бұрын
Thank you for your videos Philipp! I always learn something new!
@PhilippLackner
@PhilippLackner 10 ай бұрын
Happy to help!
@abada-s
@abada-s 10 ай бұрын
++
@tch.777
@tch.777 10 ай бұрын
++
@princeneo294
@princeneo294 10 ай бұрын
Philipp doing what Philipp does, Thanks
@user-tx2lx8jc1k
@user-tx2lx8jc1k 10 ай бұрын
Philip woke up and decided to show the facts 😅
@GS-wf1cp
@GS-wf1cp 2 ай бұрын
Mate I can't explain how much I love your content
@TravelVideos1234
@TravelVideos1234 10 ай бұрын
One of the thing to keep in mind is that you should be injecting the dispatcher. That way you can inject test dispatcher while writing unit tests
@PhilippLackner
@PhilippLackner 10 ай бұрын
yep
@eugenepopovich2264
@eugenepopovich2264 10 ай бұрын
You should not catch generic exception in the suspend method, such as coroutine may throw `CancellationException` to interrupt invocation
@PhilippLackner
@PhilippLackner 10 ай бұрын
Yes I covered that in a separate video, but I thought not to further overcomplicate this one with an additional non-trivial concept :)
@aliaksandrbohush5257
@aliaksandrbohush5257 9 ай бұрын
If your try-catch block can catch a cancellation exception, then the code is already written incorrectly. The block must catch code exceptions inside the corroutine builder or the block must wrap the topmost corroutine builder - the parent.
@aliaksandrbohush5257
@aliaksandrbohush5257 9 ай бұрын
@@PhilippLackner What is the video?
@johnalejandrogarciaarias9756
@johnalejandrogarciaarias9756 9 ай бұрын
Really useful. Thank you Philipp. Please more videos like this.
@nesletchimaew9209
@nesletchimaew9209 9 ай бұрын
i've been researching coroutine context for the past 5 days 😮
@yusuforhan6753
@yusuforhan6753 10 ай бұрын
Thank you Philipp, your videos are very valuable to us.🎉
@radosawjuszczyk638
@radosawjuszczyk638 4 ай бұрын
seeing `for(i in 1 .. 5){}` instead of `repeat(5) {}` hurts my eyes :
@xemic673
@xemic673 9 ай бұрын
interesting contents! It was useful tips. Especially 'suspend function call' icon in Android Studio. Thanks philipp
@ezzeldin101
@ezzeldin101 10 ай бұрын
Thanks for the info!
@Daaaaaaavid
@Daaaaaaavid 10 ай бұрын
Coroutines and supend functions are the most difficult thing to me to understand since Android 1.x
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
Same here. RxJava is easy comparing to coroutines.
@SerhiiSolodilov
@SerhiiSolodilov 10 ай бұрын
Tightening yourself to other library implementations isn't a good recommendation.
@ahmadhamwi4081
@ahmadhamwi4081 10 ай бұрын
A small use case that could lead to blocking code inside the library would mess the app up. I agree with you, even though his video is on point.
@bigman2127
@bigman2127 10 ай бұрын
I agree with all the points provided, but what if a repository method does large mapping stuff / CPU work / multiple calls to Room's DAO? Should i wrap a method with withContext(...) or put withContext(...) inside mappers and DAOs?
@PhilippLackner
@PhilippLackner 10 ай бұрын
If mapping is CPU heavy, the mapping function should switch the context to the default dispatcher
@Coden55
@Coden55 10 ай бұрын
@@PhilippLackner why not computation dispatcher?
@PhilippLackner
@PhilippLackner 10 ай бұрын
@@Coden55 sorry, typo I correct it. Of course the default one
@SerhiiSolodilov
@SerhiiSolodilov 10 ай бұрын
There is no such thing as light computation on UI thread. Any computation on it will result in a frame drop, it just a question when and how many frames will be dropped.
@MisterBPK
@MisterBPK 9 ай бұрын
I faced this problem. Thanks for the detailed video 😍
@johnkenedy
@johnkenedy 8 ай бұрын
Great video again :3
@raja_uma1r
@raja_uma1r 10 ай бұрын
Amazing content as usual, Consider making a video on how to retrieve data from a suspend function via flow or callback functions.
@radosawjuszczyk638
@radosawjuszczyk638 9 ай бұрын
You can use repeat(5) {} instead of that for
@GabrielTrifa
@GabrielTrifa 6 ай бұрын
excellent video!
@Hmmm964
@Hmmm964 10 ай бұрын
Hey, how does retrofit switch to the background thread? Is there any official source that declares that?
@Naxomiun
@Naxomiun 10 ай бұрын
For the people out there: This does not mean that you should not take care of your threads just because there is a call to network through retrofit at the end of your logic. You would end up executing your entire code at the scope default dispatcher; probably Main.Inmediate.
@trollberserker1515
@trollberserker1515 9 ай бұрын
this is absurd situation you imagined people do not normally put all blocking logic inside one function terminated with retrofit call. you should have your blocking code in separate main-safety functions
@Naxomiun
@Naxomiun 9 ай бұрын
​​​@@trollberserker1515what? Its really common to map data models into domain/ui models, merge lists from two endpoints, or just formatting some info before sending it to an endpoint. If you dont handle your threads you'll execute all this logic in your main thread. Its simple to understand. Retrofit switches your dispatcher right before making a net call.
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
Still, if those lists are not long (arbitrary, YMMV) then mapping/iterating over them on main thread is acceptable.
@mitulsheth
@mitulsheth 9 ай бұрын
Very useful and trusted
@devatrii
@devatrii 10 ай бұрын
Can you change that yellow lamp to green one 💚
@alexbecar977
@alexbecar977 10 ай бұрын
I'm a little confused sorry, when you say that that the non suspending blocking part of a corutine won't block the underlying thread you mean it won't block the main ui thread right? The IO thread on which the corutine runs on will be blocked by the synchronous code in the coroutine until the coroutine reaches a suspending point?
@PhilippLackner
@PhilippLackner 10 ай бұрын
Not the whole thread will be blocked, just the single coroutine. You can launch lots of Coroutines on the same thread which will all run independently
@alexbecar977
@alexbecar977 10 ай бұрын
@@PhilippLackner Thanks a lot
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
​@@PhilippLacknerindependently? You mean concurrently or parallel?
@Pavel-wj7gy
@Pavel-wj7gy 28 күн бұрын
@@marianpazdzioch5437 Concurrently, not in parallel. Parallel run implies using multiple CPU cores, not threads.
@Revitalish
@Revitalish 3 ай бұрын
it wasn't that clear.. so the coroutine scope should only be written inside a suspend function? not from the repo's function and not from the ViewModel where you call the repo function?
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
6:43 "even if it would switch to main dispatcher this would not be a problem" how come?
@tegarsubkhanfauzi4641
@tegarsubkhanfauzi4641 10 ай бұрын
Please make a tutorial how to build android tv with jetpack compose.. thaanks ❤❤❤
@nomejodas2978
@nomejodas2978 8 ай бұрын
Why try-catch in the Repository? Adding this error handling logic should be located in the Use Case
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
It definitely depends
@ko3akzhn
@ko3akzhn 9 ай бұрын
When designing a public api, what would be the best approach to let the user know that he don't need to use with Context? Or Public api should be always mainsafe?
@PhilippLackner
@PhilippLackner 9 ай бұрын
That's the concept, the user should be able to rely on your API properly switching the dispatcher
@jimpauloovejera2599
@jimpauloovejera2599 10 ай бұрын
Hey Phil, do some magic on compose UI!
@KaushalDhruw
@KaushalDhruw 9 ай бұрын
Holy cow, I am one of those who used it incorrectly.
@nsshurtz
@nsshurtz 9 ай бұрын
So, this information is really useful, however, if every suspend function is supposed to be Main Safe, then why should we not switch off of the main thread ASAP and onto the default thread? After all, if the Main thread is for doing UI work, then why do non-UI work on it?
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
Because it would be a nightmare from maintenance of that code point of view. Technically you could switch every list iteration to non-main thread but in reality nobody does that.
@mesutemrecelenk5447
@mesutemrecelenk5447 10 ай бұрын
Thanks phlipp for this useful video. I want to ask a question about this topic. I have a countdown timer in whole app that in activity onCreate. This timer is resetting at user interaction. This timer must be in io thread? Is it necessary?
@dineshvaithyalingamgangath5586
@dineshvaithyalingamgangath5586 10 ай бұрын
But is it a good idea to give this control to retrofit ? I mean, it's retrofit and yes we can trust it, but what we are using other libs which are fetching or doing something isn't it better for us to do this change ourselves?
@marianpazdzioch5437
@marianpazdzioch5437 7 ай бұрын
Then check THAT library.
@tuhinbhowmick8424
@tuhinbhowmick8424 10 ай бұрын
Nice One
@forest__fires
@forest__fires 10 ай бұрын
i did not get the point.. please
@damercy
@damercy 10 ай бұрын
Is there any downside if we wrap a suspending function with a with context(someDispatcher) anyway? For example: I've a room DAO and in the repository implementation, I wrap my dao call with a with context() block despite knowing room calls are done in background thread.
@PhilippLackner
@PhilippLackner 10 ай бұрын
Not a performance downside, but overdoing this makes the code less readable since every withContext adds another indentation and line of code
@Abdulrahman-uk9ny
@Abdulrahman-uk9ny 10 ай бұрын
Can you please record your videos in 4k?
@saeedsharif2463
@saeedsharif2463 10 ай бұрын
@philip please tell me why jetpack compose fell laggy please one vadeos on this
@ohiorenuaaigboje7500
@ohiorenuaaigboje7500 10 ай бұрын
Now i know why my code is lagging
@mirniyazulhaque3583
@mirniyazulhaque3583 10 ай бұрын
Brother teach us backend as well apart from firebase
@Shubhamkumar-ee8mi
@Shubhamkumar-ee8mi 10 ай бұрын
Thank you a lot It will really help me But i have one doubt because before that I always switch context to IO in repository. It means we dont need to switch context to IO when making http request using retrofit ? Yes or No and explain please
@PhilippLackner
@PhilippLackner 10 ай бұрын
Correvt, retrofit does that
@emmagetsu7369
@emmagetsu7369 9 ай бұрын
I have a doubt when making a splashscreen when producing on my cell phone, it installs 2 apps, one with the splashscreen and the other with the normal one. And if I uninstall one, both are gone
@user-gl8nt6ls2c
@user-gl8nt6ls2c 10 ай бұрын
😃
@giovankabisano2266
@giovankabisano2266 10 ай бұрын
3 Clean Code Hacks I Bet You Didn't Know (Kotlin & Android)
12:30
Philipp Lackner
Рет қаралды 27 М.
ОБЯЗАТЕЛЬНО СОВЕРШАЙТЕ ДОБРО!❤❤❤
00:45
Son ❤️ #shorts by Leisi Show
00:41
Leisi Show
Рет қаралды 10 МЛН
Logo Matching Challenge with Alfredo Larin Family! 👍
00:36
BigSchool
Рет қаралды 20 МЛН
Советы на всё лето 4 @postworkllc
00:23
История одного вокалиста
Рет қаралды 5 МЛН
The Essence of Coroutines
8:10
Dave Leeds
Рет қаралды 9 М.
MVVM vs. MVI - Understand the Difference Once and for All
18:40
Philipp Lackner
Рет қаралды 38 М.
THIS Compose-State Mistake Leads to Problems In Your Code
7:58
Philipp Lackner
Рет қаралды 41 М.
The Top 3 State Management Mistakes On Android
14:30
Philipp Lackner
Рет қаралды 23 М.
Kotlin Design Patterns and Best Practices | Talking Kotlin
40:40
Kotlin by JetBrains
Рет қаралды 26 М.
Coroutines: Concurrency in Kotlin
30:22
Dave Leeds
Рет қаралды 7 М.
ОБЯЗАТЕЛЬНО СОВЕРШАЙТЕ ДОБРО!❤❤❤
00:45