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

Поделиться
HTML-код
  • Опубликовано: 26 ноя 2024

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

  • @bjugdbjk
    @bjugdbjk 3 года назад +163

    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 RUclips 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 10 месяцев назад

    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!

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

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

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

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

  • @suauhwang
    @suauhwang 3 года назад +234

    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 .

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

    You don’t know how much I needed this

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

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

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

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

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

    This was a fantastic explanation and comparison. Thank you Philipp

  • @shaikhshafeen
    @shaikhshafeen Месяц назад

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

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

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

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

    The video I was waiting for. Thank you 💕

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

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

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

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

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

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

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

  • @rice-lover-android-gorani
    @rice-lover-android-gorani Год назад

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

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

    Great Video Philipp, really explained a lot, thanks

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

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

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

    That's what I am looking for amazing explanation

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

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

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

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

  • @bjugdbjk
    @bjugdbjk 3 года назад +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 3 года назад

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

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

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

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

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

    Thanks Philipp well Explained.

  • @嘿嘿嘿-z1v
    @嘿嘿嘿-z1v 4 месяца назад

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

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

    today i was looking for this topic

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

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

    Thank you very much!

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

    As usual, great video.

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

    Good stuff!! Thank you!

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

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

    Thanks for great explanation. Nice Content 👏

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

    Reactive programming, very good. Thanks 📈

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

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

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

    Very good explanations.

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

    Really really helpful. Thanks a lot

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

    This was fantastic thank you

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

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

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

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

    This is awesome 👍

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

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

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

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

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

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

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

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

    THANK YOU

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

    Thank you for this tutorial...

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

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

    You're a lifesaver

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

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

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

    Great info!

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

    Please make a video on compose states

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

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

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

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

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

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

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

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

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

    thanks

  • @ashutoshsoni6473
    @ashutoshsoni6473 3 года назад +1

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

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

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

    谢谢!

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

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

    You're the best!!

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

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

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

    Thank you boy you are gr8

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

    Need to point out that StateFlow is also null safety

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

    Waiting video about local, remote date sources )

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

    Great Video

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

    7:35 hot flow vs cold flow

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

    very nice education 👌❤❤

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

    Is the source code available?

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

    Can we replace callbacks with flows? Specifically sharedFlow?

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

    Gread Videad !!!
    😀😀

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

    amazing video

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

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

    👏👏👏

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

    What about Channels ?

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

    Could anyone share on how can MediatarLiveData be substituted with 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

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

    very helpful!!!!!!!!

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

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

    wooow more videos like this 👍

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

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

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

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

    Giga helpfull : )

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

    ❤️

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

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

  • @hashemmousavi2451
    @hashemmousavi2451 3 года назад

    Flow is cold not hot!

  • @LazyTram911
    @LazyTram911 3 года назад

    🔥t🔥o🔥p🔥