Using LiveData without LifecycleObserver





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I'm writing an app which is (attempting) to adhere to the MVVM design pattern. I'd like to observe changes to the model layer from other parts of that layer. For example



Let's say I'm exposing a list of objects from my database using room:



@Dao
interface MyDao {
@Query("SELECT * FROM myTable")
fun getAllElements(): LiveData<List<Element>>
}


I'd like to be able to observe changes like I normally would using a lifecycle owner using LiveData.observeForever(). Something like:



class BusinessLogicPartOfTheModel(private val myDao: MyDao) {
private var allElements = listOf<Element>()

init {
myDao.getAllElements().observeForever { observedElements ->
allElements = observedElements
}
}


However, I'm finding that if I register an observer like that as well as a more standard observer in a ViewModel and Fragment like this:



class MyViewModel(private val myDao: MyDao) : ViewModel() {
fun getAllElements(): LiveData<List<Elements>> {
myDao.getAllElements()
}
}

class MyFragment : Fragment() {
private val myDao /* initialized here */
private val myViewModel /* initialized here */
private val logic = BusinessLogicPartOfTheModel(myDao)

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)

val obs = Observer<List<Element>> {
// do a thing
}
myViewModel.getAllElements.observe(viewLifeCycleOwner, obs)
}
}


Only the observer in the fragment is called, and not the observer in the business logic object. I can successfully observe updates in the fragment and pass the events back down to the business logic, but that seems like an incredibly unnecessary level of indirection. Am I missing a step here or is this just unlikely to function the way I want it to?










share|improve this question





























    1















    I'm writing an app which is (attempting) to adhere to the MVVM design pattern. I'd like to observe changes to the model layer from other parts of that layer. For example



    Let's say I'm exposing a list of objects from my database using room:



    @Dao
    interface MyDao {
    @Query("SELECT * FROM myTable")
    fun getAllElements(): LiveData<List<Element>>
    }


    I'd like to be able to observe changes like I normally would using a lifecycle owner using LiveData.observeForever(). Something like:



    class BusinessLogicPartOfTheModel(private val myDao: MyDao) {
    private var allElements = listOf<Element>()

    init {
    myDao.getAllElements().observeForever { observedElements ->
    allElements = observedElements
    }
    }


    However, I'm finding that if I register an observer like that as well as a more standard observer in a ViewModel and Fragment like this:



    class MyViewModel(private val myDao: MyDao) : ViewModel() {
    fun getAllElements(): LiveData<List<Elements>> {
    myDao.getAllElements()
    }
    }

    class MyFragment : Fragment() {
    private val myDao /* initialized here */
    private val myViewModel /* initialized here */
    private val logic = BusinessLogicPartOfTheModel(myDao)

    override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    val obs = Observer<List<Element>> {
    // do a thing
    }
    myViewModel.getAllElements.observe(viewLifeCycleOwner, obs)
    }
    }


    Only the observer in the fragment is called, and not the observer in the business logic object. I can successfully observe updates in the fragment and pass the events back down to the business logic, but that seems like an incredibly unnecessary level of indirection. Am I missing a step here or is this just unlikely to function the way I want it to?










    share|improve this question

























      1












      1








      1








      I'm writing an app which is (attempting) to adhere to the MVVM design pattern. I'd like to observe changes to the model layer from other parts of that layer. For example



      Let's say I'm exposing a list of objects from my database using room:



      @Dao
      interface MyDao {
      @Query("SELECT * FROM myTable")
      fun getAllElements(): LiveData<List<Element>>
      }


      I'd like to be able to observe changes like I normally would using a lifecycle owner using LiveData.observeForever(). Something like:



      class BusinessLogicPartOfTheModel(private val myDao: MyDao) {
      private var allElements = listOf<Element>()

      init {
      myDao.getAllElements().observeForever { observedElements ->
      allElements = observedElements
      }
      }


      However, I'm finding that if I register an observer like that as well as a more standard observer in a ViewModel and Fragment like this:



      class MyViewModel(private val myDao: MyDao) : ViewModel() {
      fun getAllElements(): LiveData<List<Elements>> {
      myDao.getAllElements()
      }
      }

      class MyFragment : Fragment() {
      private val myDao /* initialized here */
      private val myViewModel /* initialized here */
      private val logic = BusinessLogicPartOfTheModel(myDao)

      override fun onActivityCreated(savedInstanceState: Bundle?) {
      super.onActivityCreated(savedInstanceState)

      val obs = Observer<List<Element>> {
      // do a thing
      }
      myViewModel.getAllElements.observe(viewLifeCycleOwner, obs)
      }
      }


      Only the observer in the fragment is called, and not the observer in the business logic object. I can successfully observe updates in the fragment and pass the events back down to the business logic, but that seems like an incredibly unnecessary level of indirection. Am I missing a step here or is this just unlikely to function the way I want it to?










      share|improve this question














      I'm writing an app which is (attempting) to adhere to the MVVM design pattern. I'd like to observe changes to the model layer from other parts of that layer. For example



      Let's say I'm exposing a list of objects from my database using room:



      @Dao
      interface MyDao {
      @Query("SELECT * FROM myTable")
      fun getAllElements(): LiveData<List<Element>>
      }


      I'd like to be able to observe changes like I normally would using a lifecycle owner using LiveData.observeForever(). Something like:



      class BusinessLogicPartOfTheModel(private val myDao: MyDao) {
      private var allElements = listOf<Element>()

      init {
      myDao.getAllElements().observeForever { observedElements ->
      allElements = observedElements
      }
      }


      However, I'm finding that if I register an observer like that as well as a more standard observer in a ViewModel and Fragment like this:



      class MyViewModel(private val myDao: MyDao) : ViewModel() {
      fun getAllElements(): LiveData<List<Elements>> {
      myDao.getAllElements()
      }
      }

      class MyFragment : Fragment() {
      private val myDao /* initialized here */
      private val myViewModel /* initialized here */
      private val logic = BusinessLogicPartOfTheModel(myDao)

      override fun onActivityCreated(savedInstanceState: Bundle?) {
      super.onActivityCreated(savedInstanceState)

      val obs = Observer<List<Element>> {
      // do a thing
      }
      myViewModel.getAllElements.observe(viewLifeCycleOwner, obs)
      }
      }


      Only the observer in the fragment is called, and not the observer in the business logic object. I can successfully observe updates in the fragment and pass the events back down to the business logic, but that seems like an incredibly unnecessary level of indirection. Am I missing a step here or is this just unlikely to function the way I want it to?







      android kotlin observable android-livedata






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 27 '18 at 0:55









      FutureShockedFutureShocked

      117113




      117113
























          1 Answer
          1






          active

          oldest

          votes


















          2














          You probably should be using MediatorLiveData instead.



          MediatorLiveData accepts another LiveData as source of events by adding it to the MediatorLiveData.



          You could use something like,



          val mediatorLiveData = MediatorLiveData<Item>().apply {
          addSource(yourLiveData) {
          // do something here
          }
          }


          You could also look at Transformations.



          Transformations has methods such as Transformation.map() and Transformation.switchMap() which simply uses MediatorLiveData under the hood.






          share|improve this answer
























          • This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

            – FutureShocked
            Nov 27 '18 at 17:11











          • You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

            – Archie G. Quiñones
            Nov 28 '18 at 1:07












          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%2f53491279%2fusing-livedata-without-lifecycleobserver%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You probably should be using MediatorLiveData instead.



          MediatorLiveData accepts another LiveData as source of events by adding it to the MediatorLiveData.



          You could use something like,



          val mediatorLiveData = MediatorLiveData<Item>().apply {
          addSource(yourLiveData) {
          // do something here
          }
          }


          You could also look at Transformations.



          Transformations has methods such as Transformation.map() and Transformation.switchMap() which simply uses MediatorLiveData under the hood.






          share|improve this answer
























          • This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

            – FutureShocked
            Nov 27 '18 at 17:11











          • You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

            – Archie G. Quiñones
            Nov 28 '18 at 1:07
















          2














          You probably should be using MediatorLiveData instead.



          MediatorLiveData accepts another LiveData as source of events by adding it to the MediatorLiveData.



          You could use something like,



          val mediatorLiveData = MediatorLiveData<Item>().apply {
          addSource(yourLiveData) {
          // do something here
          }
          }


          You could also look at Transformations.



          Transformations has methods such as Transformation.map() and Transformation.switchMap() which simply uses MediatorLiveData under the hood.






          share|improve this answer
























          • This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

            – FutureShocked
            Nov 27 '18 at 17:11











          • You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

            – Archie G. Quiñones
            Nov 28 '18 at 1:07














          2












          2








          2







          You probably should be using MediatorLiveData instead.



          MediatorLiveData accepts another LiveData as source of events by adding it to the MediatorLiveData.



          You could use something like,



          val mediatorLiveData = MediatorLiveData<Item>().apply {
          addSource(yourLiveData) {
          // do something here
          }
          }


          You could also look at Transformations.



          Transformations has methods such as Transformation.map() and Transformation.switchMap() which simply uses MediatorLiveData under the hood.






          share|improve this answer













          You probably should be using MediatorLiveData instead.



          MediatorLiveData accepts another LiveData as source of events by adding it to the MediatorLiveData.



          You could use something like,



          val mediatorLiveData = MediatorLiveData<Item>().apply {
          addSource(yourLiveData) {
          // do something here
          }
          }


          You could also look at Transformations.



          Transformations has methods such as Transformation.map() and Transformation.switchMap() which simply uses MediatorLiveData under the hood.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 27 '18 at 3:40









          Archie G. QuiñonesArchie G. Quiñones

          937621




          937621













          • This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

            – FutureShocked
            Nov 27 '18 at 17:11











          • You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

            – Archie G. Quiñones
            Nov 28 '18 at 1:07



















          • This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

            – FutureShocked
            Nov 27 '18 at 17:11











          • You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

            – Archie G. Quiñones
            Nov 28 '18 at 1:07

















          This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

          – FutureShocked
          Nov 27 '18 at 17:11





          This does look potentially useful in my specific case. The question was phrased slightly more around just observing livedata from a non-lifecycle owner whereas MediatorLiveData seems geared more towards observing and republishing.

          – FutureShocked
          Nov 27 '18 at 17:11













          You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

          – Archie G. Quiñones
          Nov 28 '18 at 1:07





          You really can't observe a LiveData without a lifecycle. It's the whole point of LiveData.

          – Archie G. Quiñones
          Nov 28 '18 at 1:07




















          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%2f53491279%2fusing-livedata-without-lifecycleobserver%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

          To store a contact into the json file from server.js file using a class in NodeJS

          Redirect URL with Chrome Remote Debugging Android Devices

          Dieringhausen