Should You Use Compose State or StateFlow in Your ViewModels?

2022 ж. 24 Қыр.
67 265 Рет қаралды

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...

Пікірлер
  • 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~

    @hongyihuang6856@hongyihuang6856Күн бұрын
  • was looking for your explanation for this from the time you made the reel about this. Thanks for this content

    @arfinhosain4969@arfinhosain4969 Жыл бұрын
  • Exactly man, I liked the point where we probably use some intermediate operators with Coroutines flow to simplify the logic.

    @mohammedalramlawi691@mohammedalramlawi691 Жыл бұрын
  • 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!

    @ubersticks@ubersticks Жыл бұрын
    • 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.

      @Alchemist10241@Alchemist1024111 ай бұрын
  • Thanks Philip! Your examples are so clear

    @gabrielbronzattimoro7953@gabrielbronzattimoro7953 Жыл бұрын
  • Amazing, thank you Philipp! This should be added as bonus/comment to the Building Industry-Level Apps With Multi-Module Architecture course :)

    @czerewacz@czerewacz Жыл бұрын
  • your videos are very helpful Philip, thanks! Please keep it up.

    @hamzacanbaz9910@hamzacanbaz9910 Жыл бұрын
  • 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

    @oleg12395@oleg1239511 ай бұрын
  • Best channel about android development, keep it up!

    @UsellesStudent@UsellesStudent Жыл бұрын
  • Thanks for the clear explaination. Easy to understand and much more interested in jetpack compose :)

    @user-ml6qs4zk8z@user-ml6qs4zk8z Жыл бұрын
  • 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.

    @omkarpawar1741@omkarpawar1741 Жыл бұрын
  • 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 ❤

    @hosseinbanay9716@hosseinbanay97163 ай бұрын
  • You nailed it as always 👌

    @yasserakbbach7342@yasserakbbach7342 Жыл бұрын
    • Thanks man

      @PhilippLackner@PhilippLackner Жыл бұрын
  • Thanks again @Philipp.

    @maximooze3196@maximooze3196 Жыл бұрын
  • I always want to give more thank one like. You are awesome. Thanks for another great video!

    @joelcaetano6420@joelcaetano6420 Жыл бұрын
    • Thank you!

      @PhilippLackner@PhilippLackner Жыл бұрын
  • Great accurate explanation. Applauding!

    @ARIZONAMUSIC@ARIZONAMUSIC Жыл бұрын
    • Glad it helped!

      @PhilippLackner@PhilippLackner Жыл бұрын
  • Exactly what i searched for. thx!

    @snow4dv@snow4dv4 ай бұрын
  • 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?

    @rafaelparanhos7435@rafaelparanhos74355 ай бұрын
  • You're the Best, thanks man

    @baudelioandalon@baudelioandalon Жыл бұрын
  • 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.

    @vit4mint685@vit4mint68512 күн бұрын
    • Thank you 🙏🙏

      @PhilippLackner@PhilippLackner12 күн бұрын
  • Was always wondering which was the best to use between StateFlow and Compose State, Thanks to you now I know better.

    @tonnie7079@tonnie7079 Жыл бұрын
  • Your awesome man, Make video about passing custom parameters (class,array) in compose navigation.

    @jithind-feverx2818@jithind-feverx2818 Жыл бұрын
  • Great video! I don't see the flow operators you referred to in the summary.

    @firaszuriekat8341@firaszuriekat8341 Жыл бұрын
  • Great video for saving state in SaveStateHandler , also premium content is superb✌✌✌

    @dipeshsaini6793@dipeshsaini6793 Жыл бұрын
    • Thanks!

      @PhilippLackner@PhilippLackner Жыл бұрын
  • 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.

    @MrGrebenjuk@MrGrebenjuk Жыл бұрын
    • But you don't get to use AAC viewmodel then (which you don't have to)

      @PhilippLackner@PhilippLackner Жыл бұрын
    • @@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!

      @MrGrebenjuk@MrGrebenjuk Жыл бұрын
  • 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)

    @GilTheCohen@GilTheCohen Жыл бұрын
    • Do you have a sample project that you would like to share?

      @ChrisAthanas@ChrisAthanas Жыл бұрын
    • @@ChrisAthanas Not really. If I make one, I'll share it

      @GilTheCohen@GilTheCohen Жыл бұрын
    • @@GilTheCohen sounds good

      @ChrisAthanas@ChrisAthanas Жыл бұрын
    • Not a good approach to use shared preference.

      @deepakbisht4957@deepakbisht4957 Жыл бұрын
    • @@deepakbisht4957 use any type of repository you would like

      @GilTheCohen@GilTheCohen Жыл бұрын
  • 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.

    @khiariyoussef3226@khiariyoussef3226 Жыл бұрын
    • The viewmodel is part of the UI

      @PhilippLackner@PhilippLackner Жыл бұрын
  • 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

    @geoffhuang6133@geoffhuang61333 ай бұрын
  • If you weren't exist, I wouldn't know what I will do. Thank you! Your samples are very clear and explanatory. 👍✨🎉

    @ebraratabay6836@ebraratabay683612 күн бұрын
  • Very cool video Thank You Bro

    @mustafaammar551@mustafaammar551 Жыл бұрын
  • Thanks very useful.

    @ahmadab9666@ahmadab9666 Жыл бұрын
  • 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?

    @yossimaskin4473@yossimaskin4473 Жыл бұрын
    • 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.

      @_zantetsuken_@_zantetsuken_ Жыл бұрын
    • ​@@_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

      @yossimaskin4473@yossimaskin4473 Жыл бұрын
    • @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.

      @rafaelparanhos7435@rafaelparanhos74355 ай бұрын
    • You can take a source code of combine and write your own combine function with as many arguments as you want

      @user-nd8dk8ns3z@user-nd8dk8ns3z5 ай бұрын
  • 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.

    @sergi.adamchuk@sergi.adamchuk7 ай бұрын
  • How would you save a complex object in savedstatehandle like uistate? Would you break it into several properties?

    @user-rz1hv@user-rz1hv Жыл бұрын
  • Cool, thanks 👍

    @xandrviking1113@xandrviking1113 Жыл бұрын
  • Superb!

    @safionweb@safionweb Жыл бұрын
  • thanks philipp! I learn a lot from your video!

    @jeckonly5853@jeckonly5853 Жыл бұрын
  • 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?

    @mieszkokozma4239@mieszkokozma4239 Жыл бұрын
    • 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

      @ChrisAthanas@ChrisAthanas Жыл бұрын
    • 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@deepakbisht4957 Жыл бұрын
    • @@deepakbisht4957 That depends on how slow data restoration is. If it is slow it is better to save it to state.

      @midenok@midenok10 ай бұрын
    • @@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...

      @deepakbisht4957@deepakbisht495710 ай бұрын
  • But when should we use a non saved stateflow, and when should we use saved stateflow

    @oliver_lauritsen_oa@oliver_lauritsen_oa8 ай бұрын
  • can you do tutorial "how to not re compose after back to screen" or navigatin tab if already openend in backstack

    @umardev500@umardev500Ай бұрын
  • Hi Sir! Do we really need ViewModel in compose if yes what are the advantages?

    @ahmadsamimyadgary8223@ahmadsamimyadgary82236 ай бұрын
  • 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.

    @ubersticks@ubersticks5 ай бұрын
  • How does "savedStateHandle" implement to ViewModel ? It is just calling without parameters in MainActivity.

    @denisk3852@denisk3852 Жыл бұрын
  • 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.)

    @scottbiggs8894@scottbiggs88943 ай бұрын
  • 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?

    @carlitosdroid@carlitosdroid Жыл бұрын
  • 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?

    @TheShadowvaultAwaits@TheShadowvaultAwaitsАй бұрын
  • I don't have the "terminal application" button in android studio, where can I find it?

    @aldredo5543@aldredo5543 Жыл бұрын
  • Thanks to you I switched already 😅.

    @abiodunmoses2638@abiodunmoses2638 Жыл бұрын
  • What about memory leaks. When you use State the Activity doesn't automatically unsubscribe from the State when it is destroyed.

    @pablovaldes6022@pablovaldes6022 Жыл бұрын
  • The official documentation of Jetpack compose uses MutableLiveData for private variables of the ViewModel, whilst you're Using MutableStateFlow. What's the catch?

    @kqvanity@kqvanity11 ай бұрын
  • Hi philipp can we use suspend and flow together in repo like suspend fun fetchOffersDetail(filters: String): Flow

    @adarshbinjola6430@adarshbinjola6430 Жыл бұрын
    • 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 😁

      @saria8340@saria8340 Жыл бұрын
  • 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

    @user-rz1hv@user-rz1hv Жыл бұрын
    • Not sure if there is an easy way yet, but for sure using Canvas

      @PhilippLackner@PhilippLackner Жыл бұрын
    • @@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@user-rz1hv Жыл бұрын
    • @@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

      @PhilippLackner@PhilippLackner Жыл бұрын
  • 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?

    @mesutemrecelenk5447@mesutemrecelenk5447 Жыл бұрын
    • 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

      @GN9K71@GN9K71 Жыл бұрын
    • @@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

      @mesutemrecelenk5447@mesutemrecelenk5447 Жыл бұрын
    • @@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.

      @GN9K71@GN9K71 Жыл бұрын
    • @@GN9K71 again thanks a lot 🙏

      @mesutemrecelenk5447@mesutemrecelenk5447 Жыл бұрын
  • Hi update android studio to dolphin version. The new logcat features are awesome and developer friendly.

    @vengateshm2122@vengateshm2122 Жыл бұрын
  • 7:27 so you say we need something like derived state?

    @spl420@spl4204 ай бұрын
  • Google recommending the experimental api over the stable one. Good old Android

    @0xmg@0xmg Жыл бұрын
    • its still the wild west after 10+ years

      @ChrisAthanas@ChrisAthanas Жыл бұрын
  • can someone please tell me how to do crud operation on list in StateFlow??

    @RaghavSharma-nt3hr@RaghavSharma-nt3hr6 ай бұрын
  • Can't you also make mutablestate survive process death by using remembersaveable?

    @sadiqabdulazeez3631@sadiqabdulazeez3631 Жыл бұрын
    • I think rememberSaveable {} only works in a Composable, therefore not in ViewModel.... but I could be wrong.

      @ubersticks@ubersticks Жыл бұрын
    • @@ubersticks correct

      @ChrisAthanas@ChrisAthanas Жыл бұрын
  • why its always difficult to use list inside observables. i would rather use compose state in ViewModel to reduce my stress levels.

    @RaghavSharma-nt3hr@RaghavSharma-nt3hr6 ай бұрын
  • Thanks a looooooot

    @bofu9662@bofu9662 Жыл бұрын
  • 7:13 where is the link about the flow operators?

    @Jerry-of9zj@Jerry-of9zj Жыл бұрын
    • Sorry, just added

      @PhilippLackner@PhilippLackner Жыл бұрын
  • I was searching for this question for the last week and couldn't find a good answer

    @aikin89@aikin89 Жыл бұрын
    • Hope this is now a good answer 😁

      @PhilippLackner@PhilippLackner Жыл бұрын
  • @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

      @ChrisAthanas@ChrisAthanas Жыл бұрын
    • If you're using AS Dolphin, they moved that button to some device manager tab (or similar)

      @PhilippLackner@PhilippLackner Жыл бұрын
    • @@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@ChrisAthanas Жыл бұрын
    • @@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@ericks6783 Жыл бұрын
    • @@ericks6783 yes but then I lose all the other features. Where did the stop button go?

      @ChrisAthanas@ChrisAthanas Жыл бұрын
  • 90

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 23

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 42

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 75

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 20

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 10

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 13

    @immortal_lnight@immortal_lnight Жыл бұрын
  • Should you be using view models in Compose?

    @georgemujuru1232@georgemujuru1232 Жыл бұрын
  • 5

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 81

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 30

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 22

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 85

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 16

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 86

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 82

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 45

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 29

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 71

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 8

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 96

    @immortal_lnight@immortal_lnight Жыл бұрын
  • How is 7:00 better than derivedStateOf()?

    @thebigboi5357@thebigboi5357 Жыл бұрын
    • It's not better, it's just the StateFlow equivalent and you keep the state logic in the VM

      @PhilippLackner@PhilippLackner Жыл бұрын
    • @@PhilippLackner gotcha, thanks!

      @thebigboi5357@thebigboi5357 Жыл бұрын
  • 17

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 55

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 6

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 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

    @techach3490@techach3490 Жыл бұрын
  • 100

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 51

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 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

      @ruhy99@ruhy99 Жыл бұрын
  • Should I use 'by' keyword instead of '=' viewModel.state.collectAsState().value?

    @summerwise@summerwise Жыл бұрын
  • 73

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 9

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 99

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 77

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 91

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 87

    @immortal_lnight@immortal_lnight Жыл бұрын
  • 66

    @immortal_lnight@immortal_lnight Жыл бұрын
KZhead