How to show LoadingState when using Room Livedata MVVM The Next CEO of Stack OverflowWhy is the Android emulator so slow? How can we speed up the Android emulator?Can an Android Architecture Components ViewModel compose an object from multiple LiveData returning models?Observing LiveData from ViewModelRepository to return LiveData when Room doesn't have it and instead fetches from REST APILiveData observer is triggered during runInTransaction() in Room databaseTesting LiveData Transformations?BoundService + LiveData + ViewModel best practice in new Android recommended architectureLiveData doesn't show data initiallyCannot observe null data - MVVM with LivedataLive data observer not triggered after room db query

Raspberry pi 3 B with Ubuntu 18.04 server arm64: what chip

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

Lucky Feat: How can "more than one creature spend a luck point to influence the outcome of a roll"?

How to get the last not-null value in an ordered column of a huge table?

Is it OK to decorate a log book cover?

Could a dragon use its wings to swim?

From jafe to El-Guest

What day is it again?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Can I board the first leg of the flight without having final country's visa?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Is there a way to save my career from absolute disaster?

Is there an equivalent of cd - for cp or mv

What are the unusually-enlarged wing sections on this P-38 Lightning?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Does Germany produce more waste than the US?

Does the Idaho Potato Commission associate potato skins with healthy eating?

What connection does MS Office have to Netscape Navigator?

Can Sneak Attack be used when hitting with an improvised weapon?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

Cannot shrink btrfs filesystem although there is still data and metadata space left : ERROR: unable to resize '/home': No space left on device

It is correct to match light sources with the same color temperature?

Inductor and Capacitor in Parallel

how one can write a nice vector parser, something that does pgfvecparseA=B-C; D=E x F;



How to show LoadingState when using Room Livedata MVVM



The Next CEO of Stack OverflowWhy is the Android emulator so slow? How can we speed up the Android emulator?Can an Android Architecture Components ViewModel compose an object from multiple LiveData returning models?Observing LiveData from ViewModelRepository to return LiveData when Room doesn't have it and instead fetches from REST APILiveData observer is triggered during runInTransaction() in Room databaseTesting LiveData Transformations?BoundService + LiveData + ViewModel best practice in new Android recommended architectureLiveData doesn't show data initiallyCannot observe null data - MVVM with LivedataLive data observer not triggered after room db query










1















so I'm coming from an MVP background...
What I'm basically trying to do is start a loadingView as soon as we start fetching the data from Room (SQLite), stop the loadingView when successful and all of that logic should be handled in my ViewModel (trying to keep my fragment clean) class for the Fragment.



What I've done right now is that I've got two LiveData's:



  1. My actual data that comes from the DB

  2. A livedata for the state of the fragment:

Here's what I mean:



enum HomeState
LOADING,
LIVE

private LiveData<List<SomeData>> someData;
private MutableLiveData<HomeState> homeState;


I'm observing both in my fragment and I want to have my homeStateLiveData determine whether the fragment should be displaying a loading view.. As you can probably see, this won't work as when the new data comes it immediately goes to the fragment and I can't control the homeState logic from the ViewModel










share|improve this question


























    1















    so I'm coming from an MVP background...
    What I'm basically trying to do is start a loadingView as soon as we start fetching the data from Room (SQLite), stop the loadingView when successful and all of that logic should be handled in my ViewModel (trying to keep my fragment clean) class for the Fragment.



    What I've done right now is that I've got two LiveData's:



    1. My actual data that comes from the DB

    2. A livedata for the state of the fragment:

    Here's what I mean:



    enum HomeState
    LOADING,
    LIVE

    private LiveData<List<SomeData>> someData;
    private MutableLiveData<HomeState> homeState;


    I'm observing both in my fragment and I want to have my homeStateLiveData determine whether the fragment should be displaying a loading view.. As you can probably see, this won't work as when the new data comes it immediately goes to the fragment and I can't control the homeState logic from the ViewModel










    share|improve this question
























      1












      1








      1








      so I'm coming from an MVP background...
      What I'm basically trying to do is start a loadingView as soon as we start fetching the data from Room (SQLite), stop the loadingView when successful and all of that logic should be handled in my ViewModel (trying to keep my fragment clean) class for the Fragment.



      What I've done right now is that I've got two LiveData's:



      1. My actual data that comes from the DB

      2. A livedata for the state of the fragment:

      Here's what I mean:



      enum HomeState
      LOADING,
      LIVE

      private LiveData<List<SomeData>> someData;
      private MutableLiveData<HomeState> homeState;


      I'm observing both in my fragment and I want to have my homeStateLiveData determine whether the fragment should be displaying a loading view.. As you can probably see, this won't work as when the new data comes it immediately goes to the fragment and I can't control the homeState logic from the ViewModel










      share|improve this question














      so I'm coming from an MVP background...
      What I'm basically trying to do is start a loadingView as soon as we start fetching the data from Room (SQLite), stop the loadingView when successful and all of that logic should be handled in my ViewModel (trying to keep my fragment clean) class for the Fragment.



      What I've done right now is that I've got two LiveData's:



      1. My actual data that comes from the DB

      2. A livedata for the state of the fragment:

      Here's what I mean:



      enum HomeState
      LOADING,
      LIVE

      private LiveData<List<SomeData>> someData;
      private MutableLiveData<HomeState> homeState;


      I'm observing both in my fragment and I want to have my homeStateLiveData determine whether the fragment should be displaying a loading view.. As you can probably see, this won't work as when the new data comes it immediately goes to the fragment and I can't control the homeState logic from the ViewModel







      android android-architecture-components android-mvvm






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 7 at 18:30









      MitchMitch

      10412




      10412






















          2 Answers
          2






          active

          oldest

          votes


















          1















          As you can probably see, this won't work as when the new data comes it
          immediately goes to the fragment and I can't control the homeState
          logic from the ViewModel




          You can control the homeState based on the database LiveData by putting yourself between the fragment's observer and the database's LiveData. The way you would do this would be either through a Transformation or through a MediatorLiveData.



          // with a Transformation
          // this would be the method which returns the database LiveData
          public LiveData<List<SomeData>> getDatabaseData()
          // the view should show a loading indicator
          homeState.setValue(HomeState.LOADING);
          // we don't actually map anything, we just use the map function to get
          // a callback of when the database's LiveData has finished loading
          return Transformations.map(dao.getSomeData(), list ->
          // the database has just finished fetching the data from the database
          // and after this method returns it will be available to the observer
          // in the fragment.
          // we also need to dismiss the loading indicator
          homeState.setValue(HomeState.LIVE);
          return list;
          );



          With a MediatorLiveData you would do something similar, just make the MediatorLiveData listen for the database LiveData and update the homeState in the observer it sets when you add the database LiveData as its source.



          If you want to abstract this, you could wrap the data you get from the database and the state(loading or available) into a single class and change your ViewModel to only return a LiveData with that class. The architecture components guide has an example(kind of related) on how you may do this, there they monitor the status of the network but you could easily adapt this to your database scenario.






          share|improve this answer


















          • 1





            Exactly what I was looking for and it's still easily testable, cheers

            – Mitch
            Mar 8 at 21:11


















          2














          I am using loading state in mvvm, rx, kotlin, retorfit for recyclerview.



          Here is my actual loading state.



          Here is my binding adapter for observe loading state.



          Here is my extended recyclerview class for loading state and empty view.



          Here is my xml file for bind loading state.



          Maybe you can get inspiration from my example.






          share|improve this answer























          • Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

            – Mitch
            Mar 8 at 21:10











          • Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

            – Mustafa Kuloğlu
            Mar 10 at 13:55












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050582%2fhow-to-show-loadingstate-when-using-room-livedata-mvvm%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1















          As you can probably see, this won't work as when the new data comes it
          immediately goes to the fragment and I can't control the homeState
          logic from the ViewModel




          You can control the homeState based on the database LiveData by putting yourself between the fragment's observer and the database's LiveData. The way you would do this would be either through a Transformation or through a MediatorLiveData.



          // with a Transformation
          // this would be the method which returns the database LiveData
          public LiveData<List<SomeData>> getDatabaseData()
          // the view should show a loading indicator
          homeState.setValue(HomeState.LOADING);
          // we don't actually map anything, we just use the map function to get
          // a callback of when the database's LiveData has finished loading
          return Transformations.map(dao.getSomeData(), list ->
          // the database has just finished fetching the data from the database
          // and after this method returns it will be available to the observer
          // in the fragment.
          // we also need to dismiss the loading indicator
          homeState.setValue(HomeState.LIVE);
          return list;
          );



          With a MediatorLiveData you would do something similar, just make the MediatorLiveData listen for the database LiveData and update the homeState in the observer it sets when you add the database LiveData as its source.



          If you want to abstract this, you could wrap the data you get from the database and the state(loading or available) into a single class and change your ViewModel to only return a LiveData with that class. The architecture components guide has an example(kind of related) on how you may do this, there they monitor the status of the network but you could easily adapt this to your database scenario.






          share|improve this answer


















          • 1





            Exactly what I was looking for and it's still easily testable, cheers

            – Mitch
            Mar 8 at 21:11















          1















          As you can probably see, this won't work as when the new data comes it
          immediately goes to the fragment and I can't control the homeState
          logic from the ViewModel




          You can control the homeState based on the database LiveData by putting yourself between the fragment's observer and the database's LiveData. The way you would do this would be either through a Transformation or through a MediatorLiveData.



          // with a Transformation
          // this would be the method which returns the database LiveData
          public LiveData<List<SomeData>> getDatabaseData()
          // the view should show a loading indicator
          homeState.setValue(HomeState.LOADING);
          // we don't actually map anything, we just use the map function to get
          // a callback of when the database's LiveData has finished loading
          return Transformations.map(dao.getSomeData(), list ->
          // the database has just finished fetching the data from the database
          // and after this method returns it will be available to the observer
          // in the fragment.
          // we also need to dismiss the loading indicator
          homeState.setValue(HomeState.LIVE);
          return list;
          );



          With a MediatorLiveData you would do something similar, just make the MediatorLiveData listen for the database LiveData and update the homeState in the observer it sets when you add the database LiveData as its source.



          If you want to abstract this, you could wrap the data you get from the database and the state(loading or available) into a single class and change your ViewModel to only return a LiveData with that class. The architecture components guide has an example(kind of related) on how you may do this, there they monitor the status of the network but you could easily adapt this to your database scenario.






          share|improve this answer


















          • 1





            Exactly what I was looking for and it's still easily testable, cheers

            – Mitch
            Mar 8 at 21:11













          1












          1








          1








          As you can probably see, this won't work as when the new data comes it
          immediately goes to the fragment and I can't control the homeState
          logic from the ViewModel




          You can control the homeState based on the database LiveData by putting yourself between the fragment's observer and the database's LiveData. The way you would do this would be either through a Transformation or through a MediatorLiveData.



          // with a Transformation
          // this would be the method which returns the database LiveData
          public LiveData<List<SomeData>> getDatabaseData()
          // the view should show a loading indicator
          homeState.setValue(HomeState.LOADING);
          // we don't actually map anything, we just use the map function to get
          // a callback of when the database's LiveData has finished loading
          return Transformations.map(dao.getSomeData(), list ->
          // the database has just finished fetching the data from the database
          // and after this method returns it will be available to the observer
          // in the fragment.
          // we also need to dismiss the loading indicator
          homeState.setValue(HomeState.LIVE);
          return list;
          );



          With a MediatorLiveData you would do something similar, just make the MediatorLiveData listen for the database LiveData and update the homeState in the observer it sets when you add the database LiveData as its source.



          If you want to abstract this, you could wrap the data you get from the database and the state(loading or available) into a single class and change your ViewModel to only return a LiveData with that class. The architecture components guide has an example(kind of related) on how you may do this, there they monitor the status of the network but you could easily adapt this to your database scenario.






          share|improve this answer














          As you can probably see, this won't work as when the new data comes it
          immediately goes to the fragment and I can't control the homeState
          logic from the ViewModel




          You can control the homeState based on the database LiveData by putting yourself between the fragment's observer and the database's LiveData. The way you would do this would be either through a Transformation or through a MediatorLiveData.



          // with a Transformation
          // this would be the method which returns the database LiveData
          public LiveData<List<SomeData>> getDatabaseData()
          // the view should show a loading indicator
          homeState.setValue(HomeState.LOADING);
          // we don't actually map anything, we just use the map function to get
          // a callback of when the database's LiveData has finished loading
          return Transformations.map(dao.getSomeData(), list ->
          // the database has just finished fetching the data from the database
          // and after this method returns it will be available to the observer
          // in the fragment.
          // we also need to dismiss the loading indicator
          homeState.setValue(HomeState.LIVE);
          return list;
          );



          With a MediatorLiveData you would do something similar, just make the MediatorLiveData listen for the database LiveData and update the homeState in the observer it sets when you add the database LiveData as its source.



          If you want to abstract this, you could wrap the data you get from the database and the state(loading or available) into a single class and change your ViewModel to only return a LiveData with that class. The architecture components guide has an example(kind of related) on how you may do this, there they monitor the status of the network but you could easily adapt this to your database scenario.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 9:13









          LuksprogLuksprog

          81k16174177




          81k16174177







          • 1





            Exactly what I was looking for and it's still easily testable, cheers

            – Mitch
            Mar 8 at 21:11












          • 1





            Exactly what I was looking for and it's still easily testable, cheers

            – Mitch
            Mar 8 at 21:11







          1




          1





          Exactly what I was looking for and it's still easily testable, cheers

          – Mitch
          Mar 8 at 21:11





          Exactly what I was looking for and it's still easily testable, cheers

          – Mitch
          Mar 8 at 21:11













          2














          I am using loading state in mvvm, rx, kotlin, retorfit for recyclerview.



          Here is my actual loading state.



          Here is my binding adapter for observe loading state.



          Here is my extended recyclerview class for loading state and empty view.



          Here is my xml file for bind loading state.



          Maybe you can get inspiration from my example.






          share|improve this answer























          • Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

            – Mitch
            Mar 8 at 21:10











          • Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

            – Mustafa Kuloğlu
            Mar 10 at 13:55
















          2














          I am using loading state in mvvm, rx, kotlin, retorfit for recyclerview.



          Here is my actual loading state.



          Here is my binding adapter for observe loading state.



          Here is my extended recyclerview class for loading state and empty view.



          Here is my xml file for bind loading state.



          Maybe you can get inspiration from my example.






          share|improve this answer























          • Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

            – Mitch
            Mar 8 at 21:10











          • Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

            – Mustafa Kuloğlu
            Mar 10 at 13:55














          2












          2








          2







          I am using loading state in mvvm, rx, kotlin, retorfit for recyclerview.



          Here is my actual loading state.



          Here is my binding adapter for observe loading state.



          Here is my extended recyclerview class for loading state and empty view.



          Here is my xml file for bind loading state.



          Maybe you can get inspiration from my example.






          share|improve this answer













          I am using loading state in mvvm, rx, kotlin, retorfit for recyclerview.



          Here is my actual loading state.



          Here is my binding adapter for observe loading state.



          Here is my extended recyclerview class for loading state and empty view.



          Here is my xml file for bind loading state.



          Maybe you can get inspiration from my example.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 8:49









          Mustafa KuloğluMustafa Kuloğlu

          576




          576












          • Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

            – Mitch
            Mar 8 at 21:10











          • Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

            – Mustafa Kuloğlu
            Mar 10 at 13:55


















          • Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

            – Mitch
            Mar 8 at 21:10











          • Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

            – Mustafa Kuloğlu
            Mar 10 at 13:55

















          Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

          – Mitch
          Mar 8 at 21:10





          Thanks for the answer. That will work, however, I'm trying to avoid binding data as I'm not a fan of it personally.

          – Mitch
          Mar 8 at 21:10













          Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

          – Mustafa Kuloğlu
          Mar 10 at 13:55






          Okay than. You can use like this withoud DataBinding: viewModel.loadingState.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() override fun onPropertyChanged(sender: Observable?, propertyId: Int) viewModel.loadingState.get()?.let venueList.setLoadingState(it) )

          – Mustafa Kuloğlu
          Mar 10 at 13:55


















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050582%2fhow-to-show-loadingstate-when-using-room-livedata-mvvm%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved