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~
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
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!
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 ❤
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?
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
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 =)
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.
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 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!
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.
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)
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?
@Sackhaarspalter 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
@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.
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.)
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.
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?
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.
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.
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?
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)
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 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
@@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
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 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!
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?
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
@@GG9K71 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
@@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.
The official documentation of Jetpack compose uses MutableLiveData for private variables of the ViewModel, whilst you're Using MutableStateFlow. What's the catch?
@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?
@@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.
@@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.
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?
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
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...
@@ldxyz-s1e 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...
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~
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
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!
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.
Exactly man, I liked the point where we probably use some intermediate operators with Coroutines flow to simplify the logic.
You nailed it as always 👌
Thanks man
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
❤
Amazing, thank you Philipp! This should be added as bonus/comment to the Building Industry-Level Apps With Multi-Module Architecture course :)
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?
Best channel about android development, keep it up!
was looking for your explanation for this from the time you made the reel about this. Thanks for this content
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
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 =)
Great video for saving state in SaveStateHandler , also premium content is superb✌✌✌
Thanks!
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.
Thank you 🙏🙏
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.
But you don't get to use AAC viewmodel then (which you don't have to)
@@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!
If you weren't exist, I wouldn't know what I will do. Thank you! Your samples are very clear and explanatory. 👍✨🎉
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.
The viewmodel is part of the UI
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)
Do you have a sample project that you would like to share?
@@ChrisAthanas Not really. If I make one, I'll share it
@@GilTheCohen sounds good
Not a good approach to use shared preference.
@@deepakbisht4957 use any type of repository you would like
your videos are very helpful Philip, thanks! Please keep it up.
Thanks Philip! Your examples are so clear
I always want to give more thank one like. You are awesome. Thanks for another great video!
Thank you!
12:25 Why not include the savedStateHandle["color"] = color line in the private setter for the composeColor? This would solve the issue, right?
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?
@Sackhaarspalter 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
@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.
You can take a source code of combine and write your own combine function with as many arguments as you want
Thanks for the clear explaination. Easy to understand and much more interested in jetpack compose :)
Google recommending the experimental api over the stable one. Good old Android
its still the wild west after 10+ years
why its always difficult to use list inside observables. i would rather use compose state in ViewModel to reduce my stress levels.
Your awesome man, Make video about passing custom parameters (class,array) in compose navigation.
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.)
Great video! I don't see the flow operators you referred to in the summary.
Great accurate explanation. Applauding!
Glad it helped!
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.
I don't have the "terminal application" button in android studio, where can I find it?
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?
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.
Exactly what i searched for. thx!
Was always wondering which was the best to use between StateFlow and Compose State, Thanks to you now I know better.
Thanks again @Philipp.
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.
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?
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)
How would you save a complex object in savedstatehandle like uistate? Would you break it into several properties?
for the compose state, why not use rememberSavable?
It suddenly became very Lovecraftian at 3:02. Cinoi´ - the less known Elder God :D
I get an error that the instance of my ViewModel can't get created. How do you do that. You don't provide anything for SavedStateHandle
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
Not sure if there is an easy way yet, but for sure using Canvas
@@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
@@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
How does "savedStateHandle" implement to ViewModel ? It is just calling without parameters in MainActivity.
Hi Sir! Do we really need ViewModel in compose if yes what are the advantages?
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)"?
Technically you'd need to update it with savedStateHandle[...].copy(...) and then listen to the saved state handle as flow
@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!
But when should we use a non saved stateflow, and when should we use saved stateflow
Thank you Philipp
can you do tutorial "how to not re compose after back to screen" or navigatin tab if already openend in backstack
Can't you also make mutablestate survive process death by using remembersaveable?
I think rememberSaveable {} only works in a Composable, therefore not in ViewModel.... but I could be wrong.
@@ubersticks correct
7:27 so you say we need something like derived state?
7:13 where is the link about the flow operators?
Sorry, just added
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?
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
@@GG9K71 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
@@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.
@@GG9K71 again thanks a lot 🙏
I was searching for this question for the last week and couldn't find a good answer
Hope this is now a good answer 😁
Thanks to you I switched already 😅.
You're the Best, thanks man
What about memory leaks. When you use State the Activity doesn't automatically unsubscribe from the State when it is destroyed.
The official documentation of Jetpack compose uses MutableLiveData for private variables of the ViewModel, whilst you're Using MutableStateFlow. What's the catch?
thank you
@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?
Like this: adb shell am kill com.realityexpander.composestatevsstateflow
If you're using AS Dolphin, they moved that button to some device manager tab (or similar)
@@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.
@@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.
@@ericks6783 yes but then I lose all the other features. Where did the stop button go?
Very cool video
Thank You Bro
Should I use StateFlow or LiveData with Compose?
stateflow
@@akashkv41 thanks
Is it still actual? I cann't find that button in logcat.
thanks philipp! I learn a lot from your video!
can someone please tell me how to do crud operation on list in StateFlow??
Cool, thanks 👍
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?
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
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...
@@deepakbisht4957 That depends on how slow data restoration is. If it is slow it is better to save it to state.
@@ldxyz-s1e 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...
Thanks very useful.
Should you be using view models in Compose?
Superb!
Hi update android studio to dolphin version. The new logcat features are awesome and developer friendly.
How is 7:00 better than derivedStateOf()?
It's not better, it's just the StateFlow equivalent and you keep the state logic in the VM
@@PhilippLackner gotcha, thanks!
Thanks a looooooot
90
75
24
60
96
28
23
27
42
25
85
86
79
76
33
Should I use 'by' keyword instead of '=' viewModel.state.collectAsState().value?
It's completely up to you! Did you find a preference?
20
30
68
63
29
21
22
26
if android kills the app, then be it. Its best to not create more complexity