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

Поділитися
Вставка
  • Опубліковано 7 лют 2025

КОМЕНТАРІ • 156

  • @bjugdbjk
    @bjugdbjk 3 роки тому +171

    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 3 роки тому +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 роки тому +15

      @@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 2 роки тому +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 Рік тому

      So SharedFlow is similar to Channels then?

  • @keepgoingman5829
    @keepgoingman5829 3 роки тому +5

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

  • @ashokmanis2111
    @ashokmanis2111 3 роки тому +5

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

  • @MrDonSocke
    @MrDonSocke 2 роки тому +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!

  • @Shanetim
    @Shanetim Рік тому

    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!

  • @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

  • @shaikhshafeen
    @shaikhshafeen 3 місяці тому

    Woho! I am glad you covered this topic!!! Thanks!!!
    (came to know about these while working on a project)

  • @suauhwang
    @suauhwang 3 роки тому +238

    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 3 роки тому +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 .

  • @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 😊

  • @nishant_thite
    @nishant_thite 2 роки тому +1

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

  • @quantumgaming7
    @quantumgaming7 2 роки тому +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.

  • @rice-lover-android-gorani
    @rice-lover-android-gorani Рік тому

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

  • @Somerandomnessvvv
    @Somerandomnessvvv 3 роки тому +2

    You don’t know how much I needed this

  • @iftak01
    @iftak01 3 роки тому +1

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

  • @mateuscoutinhomarim9184
    @mateuscoutinhomarim9184 2 роки тому

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

  • @pankajkhushalani
    @pankajkhushalani 3 роки тому +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

  • @louismusole1505
    @louismusole1505 3 роки тому +1

    The video I was waiting for. Thank you 💕

  • @chebbaelyes
    @chebbaelyes 3 роки тому +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 !

  • @shinyparadise
    @shinyparadise 2 роки тому

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

  • @SamRamezanli
    @SamRamezanli 3 роки тому +1

    This was a fantastic explanation and comparison. Thank you Philipp

  • @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 👏

  • @samstoyroom
    @samstoyroom 3 роки тому +36

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

    • @breakeract796
      @breakeract796 3 роки тому +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

  • @嘿嘿嘿-z1v
    @嘿嘿嘿-z1v 6 місяців тому

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

  • @codingcosmos7010
    @codingcosmos7010 3 роки тому

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

  • @pietro1901
    @pietro1901 2 роки тому

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

  • @suvojitpal4875
    @suvojitpal4875 Рік тому

    That's what I am looking for amazing explanation

  • @flowzk921
    @flowzk921 3 роки тому +1

    Great Video Philipp, really explained a lot, thanks

  • @bjugdbjk
    @bjugdbjk 3 роки тому +3

    @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 3 роки тому

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

  • @vlogan79
    @vlogan79 2 роки тому

    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.

  • @Ettoize
    @Ettoize 3 роки тому +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 3 роки тому +1

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

    • @alexkoromyslov8537
      @alexkoromyslov8537 3 роки тому +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 3 роки тому +1

      @@alexkoromyslov8537 Thank you sir 👍

  • @quantumgaming7
    @quantumgaming7 2 роки тому

    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.

  • @harishpatel1130
    @harishpatel1130 Рік тому

    As usual, great video.

  • @shohagkhan3677
    @shohagkhan3677 3 роки тому +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.

  • @MDDanishAnsariDev
    @MDDanishAnsariDev 2 роки тому +1

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

  • @Ibroximtechie
    @Ibroximtechie 26 днів тому

    Perfect. Thanks bro

  • @ashwinpatidar2878
    @ashwinpatidar2878 2 роки тому

    Thanks Philipp well Explained.

  • @bassline2029
    @bassline2029 3 роки тому

    Gread Videad !!!
    😀😀

  • @sahilmakkar2354
    @sahilmakkar2354 3 роки тому +1

    today i was looking for this topic

  • @NeerajKumar-du4rm
    @NeerajKumar-du4rm 2 роки тому

    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

  • @iand954
    @iand954 3 роки тому +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 3 роки тому

      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.

  • @jayantkumar1954
    @jayantkumar1954 3 роки тому +1

    This is awesome 👍

  • @creponnekarim2865
    @creponnekarim2865 Рік тому

    You're a lifesaver

  • @Rafael-hk9pg
    @Rafael-hk9pg 3 роки тому

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

  • @tafh7554
    @tafh7554 3 роки тому +1

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

  • @tareksellami7346
    @tareksellami7346 3 роки тому

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

  • @mondoshigua
    @mondoshigua 2 роки тому +1

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

  • @hoonjung2143
    @hoonjung2143 3 роки тому +1

    Good stuff!! Thank you!

  • @chimezieorji-unegbu7110
    @chimezieorji-unegbu7110 3 роки тому

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

  • @dedeandres455
    @dedeandres455 2 роки тому

    Thanks for great explanation. Nice Content 👏

  • @merryorte
    @merryorte 2 роки тому

    This was fantastic thank you

  • @leryan07
    @leryan07 2 роки тому

    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

  • @tohid6014
    @tohid6014 3 роки тому

    Very good explanations.

  • @followying392
    @followying392 Рік тому

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

  • @hamedhardani8302
    @hamedhardani8302 3 роки тому

    Really really helpful. Thanks a lot

  • @alanesaugarciagutierrez6025
    @alanesaugarciagutierrez6025 3 роки тому

    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

  • @RaulSC9
    @RaulSC9 3 роки тому +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 3 роки тому

      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 3 роки тому

      @@frantardencilla2908 Thanks mate, I missed that video

  • @sumit180288
    @sumit180288 3 роки тому +1

    Please make a video on compose states

  • @AutismSpectrumMsk
    @AutismSpectrumMsk Рік тому

    Thank you very much!

  • @emanuelortega5126
    @emanuelortega5126 3 роки тому +1

    Hi, thank for this excelent video, but i have a question. how we can imitate the behaviour of "MediatorLiveData" with 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

  • @JamesBond-mq7pd
    @JamesBond-mq7pd 2 роки тому

    THANK YOU

  • @JanPhilippHeinrich
    @JanPhilippHeinrich 3 роки тому

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

  • @zellonews
    @zellonews 3 роки тому

    Reactive programming, very good. Thanks 📈

  • @Christopher-pe6zj
    @Christopher-pe6zj 3 роки тому

    Great info!

  • @mohammadfekri4987
    @mohammadfekri4987 3 роки тому

    very nice education 👌❤❤

  • @Kunal-jp8tn
    @Kunal-jp8tn 3 роки тому

    Thank you for this tutorial...

  • @samstoyroom
    @samstoyroom 3 роки тому

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

  • @nsikakisaac7872
    @nsikakisaac7872 2 роки тому

    You're the best!!

  • @satdevlpr
    @satdevlpr 3 роки тому

    Great Video

  • @Alchemist10241
    @Alchemist10241 3 роки тому

    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 3 роки тому +2

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

  • @jackpaul1399
    @jackpaul1399 2 роки тому

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

  • @mkc0321
    @mkc0321 2 роки тому

    amazing video

  • @frankyjunior6005
    @frankyjunior6005 3 роки тому

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

  • @eliusmamun6481
    @eliusmamun6481 2 роки тому

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

  • @rdias002
    @rdias002 3 роки тому

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

  • @danielserrano2064
    @danielserrano2064 3 роки тому +1

    What about Channels ?

  • @noyaljose9635
    @noyaljose9635 3 роки тому

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

  • @miladhashemzadeh5626
    @miladhashemzadeh5626 3 роки тому

    Thank you boy you are gr8

  • @amineayachi335
    @amineayachi335 3 роки тому

    thanks

  • @devgo4995
    @devgo4995 3 роки тому

    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  3 роки тому +2

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

    • @devgo4995
      @devgo4995 3 роки тому

      @@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 3 роки тому

    7:35 hot flow vs cold flow

  • @xenofonkarydis6406
    @xenofonkarydis6406 2 роки тому

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

  • @shaikasif3356
    @shaikasif3356 2 роки тому

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

  • @somith16
    @somith16 3 роки тому

    wooow more videos like this 👍

  • @armandoquispeticona2410
    @armandoquispeticona2410 3 роки тому

    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.

  • @LazyTram911
    @LazyTram911 3 роки тому

    🔥t🔥o🔥p🔥

  • @anhlongnghien
    @anhlongnghien 3 роки тому

    very helpful!!!!!!!!

  • @oliver_lauritsen_oa
    @oliver_lauritsen_oa 3 роки тому

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

  • @shahhussain1448
    @shahhussain1448 2 роки тому

    👏👏👏

  • @shreyashchoudhary2637
    @shreyashchoudhary2637 3 роки тому

    Can we replace callbacks with flows? Specifically sharedFlow?

  • @ashutoshsoni6473
    @ashutoshsoni6473 3 роки тому +1

    So, no need to create channels and convert to sharedflow.

  • @tmjromao
    @tmjromao 3 роки тому

    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 3 роки тому +1

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

  • @alph8964
    @alph8964 Рік тому

    谢谢!

  • @1mYse1LF
    @1mYse1LF 2 роки тому

    Giga helpfull : )

  • @dragosciupe2928
    @dragosciupe2928 3 роки тому

    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 3 роки тому +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

  • @alissshhhh
    @alissshhhh 3 роки тому

    Waiting video about local, remote date sources )

  • @ChrisAthanas
    @ChrisAthanas 3 роки тому +1

    Is the source code available?

  • @bitwise-dev
    @bitwise-dev 2 роки тому

    Need to point out that StateFlow is also null safety

  • @pavelgera72
    @pavelgera72 9 місяців тому

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

  • @rabaka7899
    @rabaka7899 3 роки тому

    Pls do another jetpack compose video