Should You Use Compose State or StateFlow in Your ViewModels?

  Рет қаралды 69,978

Philipp Lackner

Philipp Lackner

Жыл бұрын

Should you use Compose state or StateFlow in your ViewModels? Here's the answer!
⭐ 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/premium-courses...
💻 Let me be your mentor and become an industry-ready Android developer in 10 weeks:
pl-coding.com/drop-table-ment...
Here's the video about flow operators:
• THIS Flow Mistake Will...
Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
pl-coding.com/newsletter
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/philipplackner
You like my free content? Here you can buy me a coffee:
www.buymeacoffee.com/philippl...

Пікірлер: 236
@arfinhosain4969
@arfinhosain4969 Жыл бұрын
was looking for your explanation for this from the time you made the reel about this. Thanks for this content
@ubersticks
@ubersticks Жыл бұрын
Thanks Philip! I think this was needed. It was never super clear to me why you changed your general practice for ViewModel state and this explains it well!
@Alchemist10241
@Alchemist10241 Жыл бұрын
not only he showed us why we should use state flows in view models but also he showed us how to use them properly and covered most of the edge cases.
@oleg12395
@oleg12395 Жыл бұрын
Philipp, you are the best ! I read this themes on google 3 times )) You explained it in 10 minutes !!!! Thank you !!! Very very simple and easy to understand
@hongyihuang6856
@hongyihuang6856 29 күн бұрын
Only a true master can explain things so clearly. Unlike those fake tech leads we usually see in a company, you are truly a master who knows Android development inside out~
@czerewacz
@czerewacz Жыл бұрын
Amazing, thank you Philipp! This should be added as bonus/comment to the Building Industry-Level Apps With Multi-Module Architecture course :)
@mohammedalramlawi691
@mohammedalramlawi691 Жыл бұрын
Exactly man, I liked the point where we probably use some intermediate operators with Coroutines flow to simplify the logic.
@hosseinbanay9716
@hosseinbanay9716 4 ай бұрын
I love your videos man. I wanted to become a mobile developer and decided to learn android instead of iOS because there are no iOS developers that have so many videos about almost every feature and can explain it in a such way that even a non programmer would understand it. Thank you Philipp ❤
@vit4mint685
@vit4mint685 Ай бұрын
Your channel has been so helpful. Been learning Jetpack Compose for a one-off personal use-case, and the quality and enthusiasm you emit in your content has me curious to expand my professional capacity to including App work. Best wishes towards your mentorship endeavors. Those that come across your channel are truly lucky.
@PhilippLackner
@PhilippLackner Ай бұрын
Thank you 🙏🙏
@hamzacanbaz9910
@hamzacanbaz9910 Жыл бұрын
your videos are very helpful Philip, thanks! Please keep it up.
@MichaelMossmanNZ
@MichaelMossmanNZ 18 күн бұрын
Thank you Philipp for another great vid. I'm watching nearly two years after the fact, but I still found it very useful. It's interesting that you mentioned KMM, because that's the reason I'm learning Jetpack Compose in the first place. Once I get the hang of Compose, I also need to learn the iOS side of things! I'm hoping Swift/Xcode will be Compose-friendly by now =)
@gabrielbronzattimoro7953
@gabrielbronzattimoro7953 Жыл бұрын
Thanks Philip! Your examples are so clear
@UsellesStudent
@UsellesStudent Жыл бұрын
Best channel about android development, keep it up!
@rafaelparanhos7435
@rafaelparanhos7435 6 ай бұрын
Wonderful video Philip but in the example there are few states. If we were talking about a complex screen that as multiples state wich is the best way to observe and update those changes?
@omkarpawar1741
@omkarpawar1741 Жыл бұрын
thanks for a great tutorial , your explanations are really helpful in understanding how to test our apps and all the problems we might face saving a lot of time for students like us.
@user-ml6qs4zk8z
@user-ml6qs4zk8z Жыл бұрын
Thanks for the clear explaination. Easy to understand and much more interested in jetpack compose :)
@joelcaetano6420
@joelcaetano6420 Жыл бұрын
I always want to give more thank one like. You are awesome. Thanks for another great video!
@PhilippLackner
@PhilippLackner Жыл бұрын
Thank you!
@jithind-feverx2818
@jithind-feverx2818 Жыл бұрын
Your awesome man, Make video about passing custom parameters (class,array) in compose navigation.
@firaszuriekat8341
@firaszuriekat8341 Жыл бұрын
Great video! I don't see the flow operators you referred to in the summary.
@yasserakbbach7342
@yasserakbbach7342 Жыл бұрын
You nailed it as always 👌
@PhilippLackner
@PhilippLackner Жыл бұрын
Thanks man
@dipeshsaini6793
@dipeshsaini6793 Жыл бұрын
Great video for saving state in SaveStateHandler , also premium content is superb✌✌✌
@PhilippLackner
@PhilippLackner Жыл бұрын
Thanks!
@ARIZONAMUSIC
@ARIZONAMUSIC Жыл бұрын
Great accurate explanation. Applauding!
@PhilippLackner
@PhilippLackner Жыл бұрын
Glad it helped!
@snow4dv
@snow4dv 4 ай бұрын
Exactly what i searched for. thx!
@MrGrebenjuk
@MrGrebenjuk Жыл бұрын
Yes, you can keep your view models in the shared module of the KMM project, and that's a good reason to avoid compose dependencies (unless you're going to use compose for ios, which is a bold decision). But. Swift doesn't know how to work with flows :) And you have to deal with some kind of wrappers.
@PhilippLackner
@PhilippLackner Жыл бұрын
But you don't get to use AAC viewmodel then (which you don't have to)
@MrGrebenjuk
@MrGrebenjuk Жыл бұрын
@@PhilippLackner Well. 1) Create an expect abstract class ViewModel() in the common module 2) android-specific actual abstract class ViewModel can inherit the AAC view model 3) ios-specific actual abstract class ViewModel should implement viewModelScope - just create one 4) inherit all your view models in the shared module from the one created on step 1 ... 5) profit!
@ebraratabay6836
@ebraratabay6836 Ай бұрын
If you weren't exist, I wouldn't know what I will do. Thank you! Your samples are very clear and explanatory. 👍✨🎉
@khiariyoussef3226
@khiariyoussef3226 Жыл бұрын
I personally never thought of using compose state in the viewmodel, because that should be considered as part of the UI and the business logic, and is also compose-specific.
@PhilippLackner
@PhilippLackner Жыл бұрын
The viewmodel is part of the UI
@geoff-huang
@geoff-huang 4 ай бұрын
Newer versions of Android Studio don't have the square button to kill process. Instead, you can right click anywhere on the logcat tab and find a "Kill process" option
@maximooze3196
@maximooze3196 Жыл бұрын
Thanks again @Philipp.
@tonnie7079
@tonnie7079 Жыл бұрын
Was always wondering which was the best to use between StateFlow and Compose State, Thanks to you now I know better.
@baudelioandalon
@baudelioandalon Жыл бұрын
You're the Best, thanks man
@scottbiggs8894
@scottbiggs8894 4 ай бұрын
Wow, in order to save a couple lines of typing, you only need to have exhaustive knowledge of the tiny inner details of some very esoteric code. Thank you, kotlin! I hope the junior programmers assigned to debugging my code two years from now will appreciate all the fine points and not just rip out my code and put something much easier to understand in its place. (Actually now that I think about it, in two years all this code will be obsolete as Google will have deprecated jetpack compose and stateflows in favor of the next new shiny thing.)
@GilTheCohen
@GilTheCohen Жыл бұрын
I actually extended MutableSnapshotState and mutableStateOf to create a persistent version of it - it automatically saves all values on each change (using SharedPreferences behind the scenes)
@ChrisAthanas
@ChrisAthanas Жыл бұрын
Do you have a sample project that you would like to share?
@GilTheCohen
@GilTheCohen Жыл бұрын
@@ChrisAthanas Not really. If I make one, I'll share it
@ChrisAthanas
@ChrisAthanas Жыл бұрын
@@GilTheCohen sounds good
@deepakbisht4957
@deepakbisht4957 Жыл бұрын
Not a good approach to use shared preference.
@GilTheCohen
@GilTheCohen Жыл бұрын
@@deepakbisht4957 use any type of repository you would like
@yossimaskin4473
@yossimaskin4473 Жыл бұрын
Thanks, Philipp! What would you do when the state is getting complex? 1. Saving all the data to SaveStateHandle can be a too-heavy operation 2. Combine is limited to 6 args and is not really meant to be used for a "Normal" case, As far as I know, the purpose is combining states from separate sources WDYT?
@_zantetsuken_
@_zantetsuken_ Жыл бұрын
I can answer the first one: The official documentation of jetpack compose states that you shouldnt overload your SaveStateHandle with too much information. Just use for example IDs that are lightweight and later read from the persistent storage to retrieve the corresponding values.
@yossimaskin4473
@yossimaskin4473 Жыл бұрын
​@@_zantetsuken_ Thanks. That was my conclusion too. so we can't apply the method mentioned in this video all the time. We should choose where it is necessary and choose the most lightweight value to save
@rafaelparanhos7435
@rafaelparanhos7435 6 ай бұрын
@yossimaskin4473 let's say we have a screen with 10 states. How you would do it? I have a project where we created a data class with all the atributes that are observable in the screen but when we update a single value in every place that the state is being observable the recompose occurs. So, when we have the states individual we assure that recompose only occurs when is needed.
@user-nd8dk8ns3z
@user-nd8dk8ns3z 6 ай бұрын
You can take a source code of combine and write your own combine function with as many arguments as you want
@user-rz1hv
@user-rz1hv Жыл бұрын
How would you save a complex object in savedstatehandle like uistate? Would you break it into several properties?
@mustafaammar551
@mustafaammar551 Жыл бұрын
Very cool video Thank You Bro
@sergi.adamchuk
@sergi.adamchuk 8 ай бұрын
What about if the state is a list? And I am updating an item of this list or add/remove items. What is the best practice for this case? Especially if my list is big and I do not want to recreate a new list.
@ahmadab9666
@ahmadab9666 Жыл бұрын
Thanks very useful.
@AungThiha-xj2bb
@AungThiha-xj2bb 23 күн бұрын
Thank you Philipp
@carlitosdroid
@carlitosdroid Жыл бұрын
Thanks Philip. However I don't have that `Terminate Application` button in latest version of Android Studio(Electric Eel). Do you have the same problem?
@ahmadsamimyadgary8223
@ahmadsamimyadgary8223 7 ай бұрын
Hi Sir! Do we really need ViewModel in compose if yes what are the advantages?
@pablovaldes6022
@pablovaldes6022 Жыл бұрын
What about memory leaks. When you use State the Activity doesn't automatically unsubscribe from the State when it is destroyed.
@ubersticks
@ubersticks 6 ай бұрын
It seems extremely common these days to wrap UI states into a data class and the ViewModel exposes this to the UI as a flow. It doesn't look like SavedStateHandle is recommended for a state data class without serializing it or some other additional work.
@mieszkokozma4239
@mieszkokozma4239 Жыл бұрын
Really nice topic, thanks! Regarding reason 2, don't you think that keeping the whole state (let's say that it's a complexed state object) in SavedStateHandle as a bundle (has to be parsed) is an overkill compared to keeping just the id and refetching the data needed to recreated the state once a POD occurres?
@ChrisAthanas
@ChrisAthanas Жыл бұрын
That's definitely one way to approach it And as you know Android has a dozen ways to achieve the same result and it's best to pick one and stick with it
@deepakbisht4957
@deepakbisht4957 Жыл бұрын
Well no one said you have to store the whole app state in savedStatehandle. Android documentation itself says it is used to store the minimal information that helps you to achieve the restoration of the whole controller. Suppose you are in a dentist screen for an id=5. So in that case you should save only the Id not the whole detail screen object. Using just Id you can get the data from the data from the repository...
@midenok
@midenok 11 ай бұрын
@@deepakbisht4957 That depends on how slow data restoration is. If it is slow it is better to save it to state.
@deepakbisht4957
@deepakbisht4957 11 ай бұрын
@@midenok well idk what are you trying to say. But the Android document itself says you need to store it as minimal details to restore the whole screen state...
@denisk3852
@denisk3852 Жыл бұрын
How does "savedStateHandle" implement to ViewModel ? It is just calling without parameters in MainActivity.
@jeckonly5853
@jeckonly5853 Жыл бұрын
thanks philipp! I learn a lot from your video!
@oliver_lauritsen_oa
@oliver_lauritsen_oa 9 ай бұрын
But when should we use a non saved stateflow, and when should we use saved stateflow
@xandrviking1113
@xandrviking1113 Жыл бұрын
Cool, thanks 👍
@umardev500
@umardev500 2 ай бұрын
can you do tutorial "how to not re compose after back to screen" or navigatin tab if already openend in backstack
@kqvanity
@kqvanity 11 ай бұрын
The official documentation of Jetpack compose uses MutableLiveData for private variables of the ViewModel, whilst you're Using MutableStateFlow. What's the catch?
@abiodunmoses2638
@abiodunmoses2638 Жыл бұрын
Thanks to you I switched already 😅.
@adarshbinjola6430
@adarshbinjola6430 Жыл бұрын
Hi philipp can we use suspend and flow together in repo like suspend fun fetchOffersDetail(filters: String): Flow
@saria8340
@saria8340 Жыл бұрын
it doesn't make sence bacause flow itself is encapsulation of suspandable IO/compute operation with result emition, so just return flow without suspend modifier 😁
@TheShadowvaultAwaits
@TheShadowvaultAwaits 2 ай бұрын
How does the viewmodel get the savedState if you are not passing it from the activity? Also how does this work when the state is a data class and not a single value?
@mesutemrecelenk5447
@mesutemrecelenk5447 Жыл бұрын
Thanks Philipp. Should we go on to use private val _state = mutableStateOf(LoginFormState()) val state: State = _state usage? Or must we use MutableStateFlow instead of above usage moreover?
@GN9K71
@GN9K71 Жыл бұрын
It depends on where the data comes from, how it's persisted and who listens for it's changes, for example: if there is data coming from repository then StateFlow is better to be used, if the data is used only inside composable functions and is only related to the UI(selected item of radio button and etc..) than it's OK to use mutableStateOf
@mesutemrecelenk5447
@mesutemrecelenk5447 Жыл бұрын
@@GN9K71 thanks for your response. Actually we can use MutableStateFlow instead of livedata. For getting data from api or db and set them on the compose components we can use this private val _state = mutableStateOf(LoginFormState()) val state: State = _state
@GN9K71
@GN9K71 Жыл бұрын
@@mesutemrecelenk5447 Yes, that's right but if you have multiple collectors of that data, which are not composable functions, than composlabe state cannot be used.
@mesutemrecelenk5447
@mesutemrecelenk5447 Жыл бұрын
@@GN9K71 again thanks a lot 🙏
@aldredo5543
@aldredo5543 Жыл бұрын
I don't have the "terminal application" button in android studio, where can I find it?
@safionweb
@safionweb Жыл бұрын
Superb!
@vengateshm2122
@vengateshm2122 Жыл бұрын
Hi update android studio to dolphin version. The new logcat features are awesome and developer friendly.
@spl420
@spl420 5 ай бұрын
7:27 so you say we need something like derived state?
@sadiqabdulazeez3631
@sadiqabdulazeez3631 Жыл бұрын
Can't you also make mutablestate survive process death by using remembersaveable?
@ubersticks
@ubersticks Жыл бұрын
I think rememberSaveable {} only works in a Composable, therefore not in ViewModel.... but I could be wrong.
@ChrisAthanas
@ChrisAthanas Жыл бұрын
@@ubersticks correct
@user-rz1hv
@user-rz1hv Жыл бұрын
Philipp do you know how to set one or multiple borders in compose? like we can do in css, because i didn't found anything helpful, you can basically set only all borders
@PhilippLackner
@PhilippLackner Жыл бұрын
Not sure if there is an easy way yet, but for sure using Canvas
@user-rz1hv
@user-rz1hv Жыл бұрын
@@PhilippLackner It's just insane how this simple thing may not to exist in compose, like it should be, because it fits in compose so naturally, but i think they'll definitely add it. And I checked out BorderStroke class and it seems to be pointless, because you can do it with border method on modifier
@PhilippLackner
@PhilippLackner Жыл бұрын
@@user-rz1hv depending on your use case you can also use padding + background modifiers to achieve this: Modifier.background(borderColor).padding(start = 1.dp).background(backgroundColor) This will create a left border. Doesn't work if the background should be transparent though
@RaghavSharma-nt3hr
@RaghavSharma-nt3hr 7 ай бұрын
why its always difficult to use list inside observables. i would rather use compose state in ViewModel to reduce my stress levels.
@annaberkovitch85
@annaberkovitch85 27 күн бұрын
Hi, Philipp! I know this is a year-old post, but I have a question about saving complex data using SavedStateHandle: In my ViewModel I'm using a MutableStateFlow of a data class. Normally, when I want to update one of the properties, I'm using the update function inside which I'm doing, for instance, "_cprRecordingState.update { it.copy(category = newCategory) }. Let's say I use savedStateHandle with a key "recording_state", would it be correct to update the StateFlow as following: "savedStateHandle["recording_state"] = _cprRecordingState.copy(category = newCategory)"?
@PhilippLackner
@PhilippLackner 27 күн бұрын
Technically you'd need to update it with savedStateHandle[...].copy(...) and then listen to the saved state handle as flow
@annaberkovitch85
@annaberkovitch85 27 күн бұрын
@PhilippLackner yeah, that would make sense, and it's a hassle 😅 Would probably be better to remove the properties that need to survive the process death and use them as separate StateFlows. Thank you very much!
@0xmg
@0xmg Жыл бұрын
Google recommending the experimental api over the stable one. Good old Android
@ChrisAthanas
@ChrisAthanas Жыл бұрын
its still the wild west after 10+ years
@Jerry-of9zj
@Jerry-of9zj Жыл бұрын
7:13 where is the link about the flow operators?
@PhilippLackner
@PhilippLackner Жыл бұрын
Sorry, just added
@RaghavSharma-nt3hr
@RaghavSharma-nt3hr 7 ай бұрын
can someone please tell me how to do crud operation on list in StateFlow??
@aikin89
@aikin89 Жыл бұрын
I was searching for this question for the last week and couldn't find a good answer
@PhilippLackner
@PhilippLackner Жыл бұрын
Hope this is now a good answer 😁
@ChrisAthanas
@ChrisAthanas Жыл бұрын
@8:20 Phillip uses a "stop button" in the logcat pane. I am using Android Studio Dolphin and I do not have this button. Am I forced to use the ADB commands to kill the app?
@ChrisAthanas
@ChrisAthanas Жыл бұрын
Like this: adb shell am kill com.realityexpander.composestatevsstateflow
@PhilippLackner
@PhilippLackner Жыл бұрын
If you're using AS Dolphin, they moved that button to some device manager tab (or similar)
@ChrisAthanas
@ChrisAthanas Жыл бұрын
@@PhilippLackner thank you Looks like there is no option to kill for physical devices in the device manager pane. I can't find out what they did with it, I've been googling like crazy and can't find any mention of it.
@ericks6783
@ericks6783 Жыл бұрын
@@ChrisAthanas A workaround is to switch to the old Logcat. Go to Settings -> Experimental -> (Uncheck) Enable new Logcat tool window. Then the stop button will appear.
@ChrisAthanas
@ChrisAthanas Жыл бұрын
@@ericks6783 yes but then I lose all the other features. Where did the stop button go?
@bofu9662
@bofu9662 Жыл бұрын
Thanks a looooooot
@martynasp.7331
@martynasp.7331 2 күн бұрын
UI State Flow backed by SavedStateHandle has to be the worst thing ever. SavedStateHandle is backed by Bundle, so the limit for data is 500Kb . So the ability to use SavedStateHandle as a source becomes really limited, and I would recommend against it. (Try to store some polygon data in there, imagine public transportation zones in a country/city)
@karamba6936
@karamba6936 8 күн бұрын
Is it still actual? I cann't find that button in logcat.
@thebigboi5357
@thebigboi5357 Жыл бұрын
How is 7:00 better than derivedStateOf()?
@PhilippLackner
@PhilippLackner Жыл бұрын
It's not better, it's just the StateFlow equivalent and you keep the state logic in the VM
@thebigboi5357
@thebigboi5357 Жыл бұрын
@@PhilippLackner gotcha, thanks!
@immortal_lnight
@immortal_lnight Жыл бұрын
90
@immortal_lnight
@immortal_lnight Жыл бұрын
75
@immortal_lnight
@immortal_lnight Жыл бұрын
24
@georgemujuru1232
@georgemujuru1232 Жыл бұрын
Should you be using view models in Compose?
@immortal_lnight
@immortal_lnight Жыл бұрын
80
@immortal_lnight
@immortal_lnight Жыл бұрын
22
@immortal_lnight
@immortal_lnight Жыл бұрын
20
@immortal_lnight
@immortal_lnight Жыл бұрын
86
@immortal_lnight
@immortal_lnight Жыл бұрын
27
@immortal_lnight
@immortal_lnight Жыл бұрын
68
@immortal_lnight
@immortal_lnight Жыл бұрын
96
@immortal_lnight
@immortal_lnight Жыл бұрын
85
@immortal_lnight
@immortal_lnight Жыл бұрын
81
@immortal_lnight
@immortal_lnight Жыл бұрын
97
@summerwise
@summerwise Жыл бұрын
Should I use 'by' keyword instead of '=' viewModel.state.collectAsState().value?
@immortal_lnight
@immortal_lnight Жыл бұрын
10
@immortal_lnight
@immortal_lnight Жыл бұрын
5
@immortal_lnight
@immortal_lnight Жыл бұрын
13
@immortal_lnight
@immortal_lnight Жыл бұрын
8
@immortal_lnight
@immortal_lnight Жыл бұрын
45
@immortal_lnight
@immortal_lnight Жыл бұрын
16
@techach3490
@techach3490 Жыл бұрын
hi, is there a documentation that explains the "private set" in more details please? would this code be correct as well? it's from CodeLab but i modified it like this var tasks = getWellnessTasks().toMutableStateList() private set instead of private val _tasks = getWellnessTasks().toMutableStateList() val tasks get() = _tasks.toList
@immortal_lnight
@immortal_lnight Жыл бұрын
50
@immortal_lnight
@immortal_lnight Жыл бұрын
6
@immortal_lnight
@immortal_lnight Жыл бұрын
44
@immortal_lnight
@immortal_lnight Жыл бұрын
17
@ruhy99
@ruhy99 Жыл бұрын
For states you can use var color by savedStateHandle.saveable { mutableStateOf(0xFFFFFFFF) }
@ruhy99
@ruhy99 Жыл бұрын
I normally use that since I notice it exists, the problem is that state can't have a nullable value, but it's a good practice for compose
@immortal_lnight
@immortal_lnight Жыл бұрын
77
@immortal_lnight
@immortal_lnight Жыл бұрын
9
@immortal_lnight
@immortal_lnight Жыл бұрын
99
@immortal_lnight
@immortal_lnight Жыл бұрын
92
THIS Compose-State Mistake Leads to Problems In Your Code
7:58
Philipp Lackner
Рет қаралды 37 М.
Cute Barbie Gadget 🥰 #gadgets
01:00
FLIP FLOP Hacks
Рет қаралды 50 МЛН
Каха инструкция по шашлыку
01:00
К-Media
Рет қаралды 8 МЛН
The Top 3 State Management Mistakes On Android
14:30
Philipp Lackner
Рет қаралды 21 М.
Bottom Nav Bar #03 | Material 3 | Jetpack Compose
12:21
Okay Samurai | Code-Along
Рет қаралды 8 М.
5 Fatal Coroutine Mistakes Nobody Tells You About
18:15
Philipp Lackner
Рет қаралды 84 М.
State holders and state production in the UI Layer
20:53
Android Developers
Рет қаралды 43 М.
This Is My FAVORITE Error Handling Class
28:57
Philipp Lackner
Рет қаралды 25 М.
Advanced state and side effects in Jetpack Compose
41:21
Android Developers
Рет қаралды 32 М.
Cute Barbie Gadget 🥰 #gadgets
01:00
FLIP FLOP Hacks
Рет қаралды 50 МЛН