0

I have an Activity A. In this activity I have MutableLiveData ,id. When a button is clicked, I start an Activity B through startActivityForResult(). After doing some work, I finish Activity B & the onActivityResult() method is trigger. In this method, I change the value of MutableLiveData() ,id.

id.value = 5 // ex

But the following code is not triggering:

id.observe(this, Observer {
       // do-something if triggered
    })

I suspect there is a change of owner when the Activity B is started. What should I do to trigger the observable data from onActivityResult()? Please help.

noob-Sci-Bot
  • 231
  • 5
  • 18
  • 3
    why not use 2 fragments and use shared view model scoped to lifecycle of activity that way you don't need 2 activities – Raghunandan Aug 22 '19 at 08:56
  • You can check this answer for shared view model solution: https://stackoverflow.com/a/55060912/4699509 – Natig Babayev Aug 22 '19 at 08:58
  • Can you check if the observable also works after unlock? – jobbert Aug 22 '19 at 09:01
  • @Raghunandan That would be the best practice I assume. But is there any quick fix for this current scenario? – noob-Sci-Bot Aug 22 '19 at 09:02
  • if you have the same instance of mutable live data and your are observing on the same you should be able to change the value. can you check that first. If not i suggest you use fragments – Raghunandan Aug 22 '19 at 09:09
  • Yes, this is the same instance of mutable live data which is placed in Activity A's viewModel class. – noob-Sci-Bot Aug 22 '19 at 09:11
  • there is a lib by some who has created sharedview models for activities with singleton view models and livedata. https://github.com/FarshadTahmasbi/Vita and i am not sure of the cons and pros of it. but this might help of a quick fix to share data between activities. But please look into the cons before using it in production – Raghunandan Aug 22 '19 at 09:11
  • and do read up on https://github.com/googlesamples/android-architecture-components/issues/29 – Raghunandan Aug 22 '19 at 09:11
  • Thank you for the reply, Sir! The reason observer was not triggered because I finished the parent activity before the value changed. – noob-Sci-Bot Aug 22 '19 at 10:49

0 Answers0