StateFlow vs. Flow vs. SharedFlow vs. LiveData... When to Use What?! - Android Studio Tutorial

Поделиться
HTML-код
  • Опубликовано: 30 июл 2024
  • In this video you'll learn the differences between the typical observable classes we have in Android.
    ⭐ 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 personally review your code and provide individual feedback, so it won't backfire and cost you a fortune in future:
    elopage.com/s/philipplackner/...
    Subscribe to my newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/newsletter
    Join this channel to get access to perks:
    / @philipplackner
    Regular live codings on Twitch:
    / 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...
    00:00 - Introduction
    01:46 - LiveData
    04:30 - StateFlow
    08:11 - Flow
    10:58 - SharedFlow
    16:30 - Compose state

Комментарии • 152

  • @bjugdbjk
    @bjugdbjk 2 года назад +156

    1. LiveData is an lifecycle aware obervable data holder ( means it knows the lifecycle of the activity or an fragment) use it when you play with UI elements(views).
    2. StateFlow(hot stream) does similar things like LiveData but it is made using flow by kotlin guys and only difference compare to LiveData is its not lifecycle aware but this is also been solved using repeatOnLifecycle api's, So whatever LiveData can do StateFlow can do much better with power of flow's api.
    3. SharedFlow(hot stream) - name itself says it is shared, this flow can be shared by multiple consumers, I mean if multiple collect calls happening on the sharedflow there will be a single flow which will get shared across all the consumers unlike normal flow.
    4. Flow (cold stream) - In general think of it like a stream of data flowing in a pipe with both ends having a producer and consumer running on a coroutine.

    • @smonkey001
      @smonkey001 2 года назад +6

      basically rewirte rxjava with a nicer api enable by kotlin

    • @myrmecii578
      @myrmecii578 2 года назад +9

      Hi, thanks for the explanation. I have a question tho, you said that StateFlow can do anything that LiveData does but better, can you give me an example of what it is? Because I've been using LiveData on some of my apps but never find a problem where i need to use Flow/StateFlow/SharedFlow

    • @bjugdbjk
      @bjugdbjk 2 года назад +14

      @@myrmecii578 Most important thing with flows are native to kotlin and they are not platform dependent like livedata, so if have our codebase with flows they are pretty much useful when we use KMM in future and secondly I feel the flow is having pretty good list of operators which we can seriously playaround and with coroutines support. And flows can be used in different layers of the app altogether and can be glued together in much idiomatic style.

    • @codingWithAj
      @codingWithAj Год назад +3

      Great explanation. Also, a normal Flow (cold) can be converted to a hot flow using shareIn. For example
      val latestFood: Flow = flow {
      ...
      }.shareIn(
      externalScope,
      replay = 1,
      started = SharingStarted.WhileSubscribed()
      )

    • @TusharGogna
      @TusharGogna 9 месяцев назад

      So SharedFlow is similar to Channels then?

  • @nishant_thite
    @nishant_thite 2 года назад +1

    The best yet simplest explaination. Covers the use cases and differences both! Thanks a ton Philipp.

  • @keepgoingman5829
    @keepgoingman5829 2 года назад +4

    That's what i want recently. it's legendary.
    you're a magician. thank you for everything you give the subscribers all the videos!!

  • @Shanetim
    @Shanetim 6 месяцев назад

    This video is brilliant.
    I decided to rebuild our company app using Kotlin and Jetpack Compose. You really helped me get my head around things.
    Thank you very much!

  • @MrDonSocke
    @MrDonSocke Год назад +1

    googled hours didn't found what I was looking for. 5 minutes into you video and I figured it out. Thanks mate! Love your Videos!

  • @DennisEspiritu
    @DennisEspiritu 2 года назад +3

    As someone who is new to reactive programming, this video is quite useful. LiveData, Flow, StateFlow, SharedFlow, Compose states, it all makes sense now. I'll check out another concept (Channel) and then proceed to one of your MVVM projects 😊

  • @SamRamezanli
    @SamRamezanli 2 года назад +1

    This was a fantastic explanation and comparison. Thank you Philipp

  • @ashokmanis2111
    @ashokmanis2111 2 года назад +5

    I watched lots of RUclips videos and doc but i can't understand the different. But your video is more clearly explained..thanks for the video.

  • @mohamedayad70
    @mohamedayad70 2 года назад

    Really helped me a lot as your all videos do ❤️
    Thx man and keep sharing your quality content more and more you are the best 👏

  • @louismusole1505
    @louismusole1505 2 года назад +1

    The video I was waiting for. Thank you 💕

  • @pankajkhushalani
    @pankajkhushalani 2 года назад +2

    Thanks a lot for this! I had surrounded myself with Android Jetpack libraries and wanted to check out Flow. I'll definitely try out more of SharedFlow

  • @Somerandomnessvvv
    @Somerandomnessvvv 2 года назад +2

    You don’t know how much I needed this

  • @vadymhrynyk9964
    @vadymhrynyk9964 2 года назад +1

    you are the best teacher in the world, i really hope that you continue recording video for you channel very often, i really thank to you. xD

  • @shinyparadise
    @shinyparadise Год назад

    Nice explanations dude! Your video has helped me a lot and thanks to everybody in the comments for errata.

  • @chebbaelyes
    @chebbaelyes 2 года назад +3

    Thanks for your great content ! I'm a professional Android developer but I've been working with RxJava and XML, and your videos have been a great summary of what I need to know about Compose and Coroutines !

  • @flowzk921
    @flowzk921 2 года назад +1

    Great Video Philipp, really explained a lot, thanks

  • @iftak01
    @iftak01 2 года назад +1

    You deserve more subs.. one of the best android channel

  • @tareksellami7346
    @tareksellami7346 2 года назад

    Awesome content ❤️. Can't thank you enough for your hard work

  • @user-gorani-wanna-be-developer

    I love you......
    I always have been curious of those differences.
    Thank you.

  • @mateuscoutinhomarim9184
    @mateuscoutinhomarim9184 Год назад

    Niiice man, I'm glad that I found this video only one day after I had this question myself.

  • @codingcosmos7010
    @codingcosmos7010 2 года назад

    You make real Topics man... keep making keep growing...😀😀

  • @Rafael-hk9pg
    @Rafael-hk9pg 2 года назад

    Nice video, thanks Philipp! It would help me more if you would describe real world examples of when to use what type of flow.

  • @suauhwang
    @suauhwang 2 года назад +229

    Big mistake here: Neither LiveData nor StateFlow keep the state alive on activity re-creation/rotation. That's the job of the ViewModel.
    I'm not trying to nitpick here, but you've mentioned it several times (2:20, 6:22) and it's definitely a mistake.
    The purpose is LiveData/StateFlow is to call you back when the value changes, instead of you repeatedly checking if changes happened.
    This is called the observer pattern, where LiveData/StateFlow is the observable (holding the value you are interested in) and your activity is the observer (someone who is interested in changes)
    Again, if you put LiveData/StateFlow into the activity or fragment instead of the ViewModel, then the state will be lost on screen-rotation.

    • @ChungHoang-qy3xl
      @ChungHoang-qy3xl 2 года назад +3

      that's right.

    • @jackpaul1399
      @jackpaul1399 2 года назад +2

      Thanks! Where can I download the sample code in the videos?

    • @MrEmailll
      @MrEmailll 2 года назад +2

      Noop, you are made mistake. ViewModel just keep single instance of liveData when you rotate device. If you will create liveData in Fragment or Activity, it won't work as you expect because will be created new instance of liveData. Am i right?

    • @suauhwang
      @suauhwang 2 года назад +8

      @@MrEmailll correct, the ViewModel/ViewModelProvider are responsible for keeping a single instance alive over activity re-creations.
      LiveData doesn't do that by itself, LiveData is just a lifecycle aware observable, if you put it in a fragment or activity you will get a new instance on activity re-creation just like any other member of fragements/activities

    • @ChungHoang-qy3xl
      @ChungHoang-qy3xl 2 года назад +2

      @@MrEmailll that's right .

  • @pietro1901
    @pietro1901 2 года назад

    You're genius man I'm coming from c# loving your videos

  • @shohagkhan3677
    @shohagkhan3677 2 года назад +4

    Thanks for the very important topic you covered. Do you have any video where you showed how to use StateFlow or SharedFlow with Retrofit api call along with state handle using Kotlin sealed class?
    If not, please (if possible) make a video on CRUD by showing how to combine all those things using MVVM pattern.

  • @quantumgaming7
    @quantumgaming7 Год назад +1

    6:59 the reason of preferring flow over livedata is not having more operators basically you can do that with live data too but in livedata that happens on main thread but in flows you can switch the context whereever you want.

  • @user-ml6qs4zk8z
    @user-ml6qs4zk8z 15 дней назад

    Thanks for explaination in detail. I'll try it later :)

  • @dedeandres455
    @dedeandres455 2 года назад

    Thanks for great explanation. Nice Content 👏

  • @hamedhardani8302
    @hamedhardani8302 2 года назад

    Really really helpful. Thanks a lot

  • @hoonjung2143
    @hoonjung2143 2 года назад +1

    Good stuff!! Thank you!

  • @ashwinpatidar2878
    @ashwinpatidar2878 2 года назад

    Thanks Philipp well Explained.

  • @noahortega
    @noahortega Год назад

    This was fantastic thank you

  • @harishpatel1130
    @harishpatel1130 Год назад

    As usual, great video.

  • @suvojitpal4875
    @suvojitpal4875 9 месяцев назад

    That's what I am looking for amazing explanation

  • @AutismSpectrumMsk
    @AutismSpectrumMsk 10 месяцев назад

    Thank you very much!

  • @tohid6014
    @tohid6014 2 года назад

    Very good explanations.

  • @samstoyroom
    @samstoyroom 2 года назад +36

    One important feature of SharedFlow is that it will emit the same value, and StateFlow won't.

    • @breakeract796
      @breakeract796 2 года назад +17

      I think it not completely correct.
      SharedFlow can be replay for many consumers whereas StateFlow won't.
      Actually you can emit the same value for the StateFlow, just need the other object address.
      The main different usage between SharedFlow vs StateFlow is:
      - SharedFlow is hold the Event
      - StateFlow is hold the Data

  • @chimezieorji-unegbu7110
    @chimezieorji-unegbu7110 2 года назад

    For the umpteenth time, you are amazing. Any plans soon of making videos for Espresso UI tests for jetpack compose?

  • @JanPhilippHeinrich
    @JanPhilippHeinrich 2 года назад

    Hi Philipp, thanks for your great content. Could you maybe make a video about the current state of using Google Maps with Jetpack and Compose? It seems that Google Maps are not really working well with Compose right now...

  • @Christopher-pe6zj
    @Christopher-pe6zj 2 года назад

    Great info!

  • @jayantkumar1954
    @jayantkumar1954 2 года назад +1

    This is awesome 👍

  • @Kunal-jp8tn
    @Kunal-jp8tn 2 года назад

    Thank you for this tutorial...

  • @sahilmakkar2354
    @sahilmakkar2354 2 года назад +1

    today i was looking for this topic

  • @MaisUmSomente
    @MaisUmSomente 2 года назад

    Reactive programming, very good. Thanks 📈

  • @JamesBond-mq7pd
    @JamesBond-mq7pd 2 года назад

    THANK YOU

  • @mohammadfekri4987
    @mohammadfekri4987 2 года назад

    very nice education 👌❤❤

  • @emanuelortega5126
    @emanuelortega5126 2 года назад +1

    Hi, thank for this excelent video, but i have a question. how we can imitate the behaviour of "MediatorLiveData" with flow?

  • @alph8964
    @alph8964 Год назад

    谢谢!

  • @armandoquispeticona2410
    @armandoquispeticona2410 2 года назад

    Hi Philipp!
    I have a doubt, I would like to know if It's possible to reduce request to server(p.g firebase-firestore) when I use flowState. Now, I'm using livedata but I do many request...so with FlowState with 1 request I could to keep the fresh data?
    This case is for a Social App.

  • @miladhashemzadeh5626
    @miladhashemzadeh5626 2 года назад

    Thank you boy you are gr8

  • @satdevlpr
    @satdevlpr 2 года назад

    Great Video

  • @nsikakisaac7872
    @nsikakisaac7872 2 года назад

    You're the best!!

  • @anhlongnghien
    @anhlongnghien 2 года назад

    very helpful!!!!!!!!

  • @frankyjunior6005
    @frankyjunior6005 2 года назад

    hopefully you can do the same in jetpack compose because i still confusing how to observe single event by using Channel from viewmodel

  • @jackpaul1399
    @jackpaul1399 2 года назад

    Thanks! Your video is great, where can I download the sample code in the video for testing?

  • @creponnekarim2865
    @creponnekarim2865 Год назад

    You're a lifesaver

  • @mkc0321
    @mkc0321 2 года назад

    amazing video

  • @rdias002
    @rdias002 2 года назад

    For one time events such as error toasts, should I use SharedFlow or Kotlin Channels?

  • @1mYse1LF
    @1mYse1LF 2 года назад

    Giga helpfull : )

  • @alanesaugarciagutierrez6025
    @alanesaugarciagutierrez6025 2 года назад

    Sharedflow save the State in screen rotation? For example if i use it for the Hello World example, the TextView will have the "Hello World!" or the "Shared flow"? After screen rotation

  • @Ettoize
    @Ettoize 2 года назад +7

    Wish you would've mentioned Channels in this video too, to send events, etc.
    I used Coroutines Channels in one of my projects and from what I understand they are similar to SharedFlow

    • @symekoo7
      @symekoo7 2 года назад +1

      Me too, and I'd like to know, which is better for this kind of 'event' operations

    • @alexkoromyslov8537
      @alexkoromyslov8537 2 года назад +10

      SharedFlow as a hot flow will emit data even if no one listening. Channel will hold data till someone consumes it. So if your view not ready to receive an event and sharedFlow emits it, the event will be lost. So channels are better to send one time events. Obviously you can set reply count for shared flow, but then your event will be repeated .

    • @symekoo7
      @symekoo7 2 года назад +1

      @@alexkoromyslov8537 Thank you sir 👍

  • @somith16
    @somith16 2 года назад

    wooow more videos like this 👍

  • @NeerajKumar-du4rm
    @NeerajKumar-du4rm Год назад

    THANK YOU SO MUCH!!! PLEASE HELP I have created single activity by watching your Clean MVVM Notes video, it uses Compose navigation, Problem is there is a button on B screen to send email, so it needs to startActivity(context,intent), but I cannot get context, i tried all of these couldnt get it working, so is it possible that I can fire event from Compose screen B and startActivity is done by MainActivity? this context is making it so hard

  • @tafh7554
    @tafh7554 2 года назад +1

    bro i'am suggest you to create video about offline first / caching data from api to room db, thank you

  • @amineayachi335
    @amineayachi335 2 года назад

    thanks

  • @followying392
    @followying392 7 месяцев назад

    Hello, i want to use a variable across activities , which video i should watch from your playlist, thank you !

  • @samstoyroom
    @samstoyroom 2 года назад

    What's the difference between MutableStateFlow and MutableStateOf? Can you make a video for that? THANK YOU!

  • @shreyashchoudhary2637
    @shreyashchoudhary2637 2 года назад

    Can we replace callbacks with flows? Specifically sharedFlow?

  • @eliusmamun6481
    @eliusmamun6481 Год назад

    Could anyone share on how can MediatarLiveData be substituted with SharedFlow?

  • @quantumgaming7
    @quantumgaming7 Год назад

    11:01 would like to add something when tou rotate screen your activity is getting recreated so to normal flow it’s just new new subscriber and you have to request the data again.

  • @leryan07
    @leryan07 Год назад

    Can you show how to make an indefinite snackbar:
    1. Survive screen rotation
    2. Show again, if action performed
    Use case:
    If we were to use a snackbar for an error when fetching data
    I can only get one or the other to work

  • @bassline2029
    @bassline2029 2 года назад

    Gread Videad !!!
    😀😀

  • @bjugdbjk
    @bjugdbjk 2 года назад +2

    @8:06 StateFlows are hot unlike normal flow in a way like they can live without any active consumer (bcz data is produced outside of the stream and then sent into the flow) but it's not like it will emit without calling collect on it !!

    • @alexkoromyslov8537
      @alexkoromyslov8537 2 года назад

      Hot streams will emit values even if no one collecting it by definition of hot flow.

  • @sumit180288
    @sumit180288 2 года назад +1

    Please make a video on compose states

  • @vlogan79
    @vlogan79 Год назад

    You say don't use LiveData, but many of the modern Room tutorials and documentation still use LiveData for returning live data from a database.

  • @iand954
    @iand954 2 года назад +3

    Sorry, which way is better to passing data (List of data) "retrofit -> repository -> viewmodel -> view(compose)"? I want to periodically call data by WorkManager. Thank You.

    • @AshutoshSinghedm
      @AshutoshSinghedm 2 года назад

      Depends on the use case.
      If its a single shot then normal data type
      If its a short poll or web hook something that works with live data or flow.

  • @KhoaNguyen-ou8xg
    @KhoaNguyen-ou8xg 2 года назад

    Just come back to the Android after months working in the backend domain, these flow stuff is really confusing, i also heard that there are channels and callbackflow

  • @tmjromao
    @tmjromao 2 года назад

    Hard to understand what emit implies. Example, emit ("Item 1"), means the sw continuously emits the string (thousands, millions of times, exact number depends on the machine, CPU)? the program collects one of those strings, although on the background the software keeps emitting "thousands" of strings. Can the continuous emission impact the performance of the app?

    • @ChrisAthanas
      @ChrisAthanas 2 года назад +1

      It's important to know the difference between cold flows and hot flows

  • @alissshhhh
    @alissshhhh 2 года назад

    Waiting video about local, remote date sources )

  • @noyaljose9635
    @noyaljose9635 2 года назад

    So what's the difference between channel and sharedflow?🤔

  • @RaulSC9
    @RaulSC9 2 года назад +1

    Excellent summary. As for many other people, you are a reference in Android programming and I would like to know your opinion. Do you think we should continue using XML or is it definitely better to use Jetpack compose in new projects? Best regards and thanks.

    • @frantardencilla2908
      @frantardencilla2908 2 года назад

      In one of his videos he said that JetpackCompose is not suitable for complex projects, at least not yet. But I´m not sure if that´s still the case.

    • @RaulSC9
      @RaulSC9 2 года назад

      @@frantardencilla2908 Thanks mate, I missed that video

  • @shahhussain1448
    @shahhussain1448 2 года назад

    👏👏👏

  • @safionweb
    @safionweb 2 года назад

    ❤️

  • @MDDanishAnsariDev
    @MDDanishAnsariDev Год назад +1

    Why StateFlow needs to be called on `launchWhenStarted()` not on `launch()`?

  • @xenofonkarydis6406
    @xenofonkarydis6406 Год назад

    (Irrelevant question) What software do you use for the recoding?

  • @dragosciupe2928
    @dragosciupe2928 2 года назад

    I started android dev about 2 months ago and i learnt a lot of technical stuff,but how can i improve my ui/ux skills,because everybody puts the accent on the technical part
    I would love your advice if that's possible because im really struggling with the design part,basically making an app look good and professional

    • @ChrisAthanas
      @ChrisAthanas 2 года назад +1

      Design is a completely separate skill
      You can look at other apps and try to copy their style
      It takes practice and time to learn design
      Usually most developers work with designers bc it's such a different skill set

  • @pavelgera72
    @pavelgera72 3 месяца назад

    Благодарю за урок

  • @danielserrano2064
    @danielserrano2064 2 года назад +1

    What about Channels ?

  • @RRRazzzaRRR
    @RRRazzzaRRR 2 года назад

    🔥t🔥o🔥p🔥

  • @devgo4995
    @devgo4995 2 года назад

    How do I safely collect a Flow from Custom View or ViewHolder class? What's the right lifecycle scope to handle it. Ex: using your example Flow to simulate a Timer.

    • @PhilippLackner
      @PhilippLackner  2 года назад +2

      That's not the job of the view. It should be maintained in the viewmodel

    • @devgo4995
      @devgo4995 2 года назад

      @@PhilippLackner But for example PagingDataAdapter where the collection is immutable from outside (PagingData) is not possible if I handle it from the ViewModel (Simulate a timer with a Flow). The question would rather be; Should a Flow be mandatorily tied to the Lifecycle when it is collected?

  • @babythedude
    @babythedude 2 года назад

    7:35 hot flow vs cold flow

  • @Alchemist10241
    @Alchemist10241 2 года назад

    11:02 Why are you using collectLatest as a terminal operator?, collect can do the same job.
    Maybe I misunderstood something about collect operator. If anyone know the difference? Please comment here

    • @ChrisAthanas
      @ChrisAthanas 2 года назад +2

      CollectLatest gets the most recent value emitted, and collect will take every value in the order it was emitted

  • @ChrisAthanas
    @ChrisAthanas 2 года назад +1

    Is the source code available?

  • @rabaka7899
    @rabaka7899 2 года назад

    Pls do another jetpack compose video

  • @tula1308
    @tula1308 2 года назад

    Greate

  • @mondoshigua
    @mondoshigua Год назад +1

    🙌🏻🇨🇴🧔🏻👍🏼🤝🏼👉🏼🖥️📱 Saludos desde Colombia.

  • @shaikasif3356
    @shaikasif3356 Год назад

    I’m unable to hear what I made???? HELP

  • @oliver_lauritsen_oa
    @oliver_lauritsen_oa 2 года назад

    I’m using Java for android apps I don’t know kotlin it’s too hard to learn

  • @mehdiparsaei1867
    @mehdiparsaei1867 2 года назад

    Great Man! Thank you for teaching!
    Could I contribute in your freelancer project totally free? I would love working with you.
    I look forward to hearing from you.

  • @ubersticks
    @ubersticks 2 года назад

    Is this code available?