How can I share LiveData between multiple ViewModels?How to share an instance of LiveData in android app?Why is the Android emulator so slow? How can we speed up the Android emulator?How can I use WearableActivity with LiveData and ViewModelObserving LiveData from ViewModelHow to use ViewModel in Android with LiveData from repository (DB/network)?How to create LiveData which emits a single event and notifies only last subscribed observer?LiveData observer not getting triggered in KotlinBoundService + LiveData + ViewModel best practice in new Android recommended architectureHow does LiveData works in this case?How to have separate instance of ViewModel in each Fragment and have shared data as well between ViewmodelsCreate ViewModel with Application

Is verification of a blockchain computationally cheaper than recreating it?

Plotting Chebyshev polynomials using PolarPlot and FilledCurve

Feedback diagram

Overprovisioning SSD on ubuntu. How? Ubuntu 19.04 Samsung SSD 860

How to get maximum number that newcount can hold?

Why did the United States not resort to nuclear weapons in Vietnam?

Is Illustrator accurate for business card sizes?

What does the "きゃ" in "していきゃがらなかった" stand for?

How to avoid a lengthy conversation with someone from the neighborhood I don't share interests with

How do I safety check that there is no light in Darkroom / Darkbag?

How to power down external drive safely

Look for an example where H is normal in K, K is characteristic in G, but H is not normal in G

Should 2FA be enabled on service accounts?

Skipping same old introductions

What's the term for a group of people who enjoy literary works?

Move label of an angle in Tikz

Define tcolorbox in math mode

"Will flex for food". What does this phrase mean?

How do I respond appropriately to an overseas company that obtained a visa for me without hiring me?

Ernie and the Superconducting Boxes

What does a number above the 'staff' mean in tablature?

How to trick a fairly simplistic kill-counter?

Password management for kids - what's a good way to start?

Can I say "Gesundheit" if someone is coughing?



How can I share LiveData between multiple ViewModels?


How to share an instance of LiveData in android app?Why is the Android emulator so slow? How can we speed up the Android emulator?How can I use WearableActivity with LiveData and ViewModelObserving LiveData from ViewModelHow to use ViewModel in Android with LiveData from repository (DB/network)?How to create LiveData which emits a single event and notifies only last subscribed observer?LiveData observer not getting triggered in KotlinBoundService + LiveData + ViewModel best practice in new Android recommended architectureHow does LiveData works in this case?How to have separate instance of ViewModel in each Fragment and have shared data as well between ViewmodelsCreate ViewModel with Application






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I've tried extracting the value into a base class and having the ViewModels extend it. When I do that, however, the Observer isn't sticking to the LiveData. For instance, when I have a parent class with LiveData:



class Base : ViewModel() 
private val _ data = MutableLiveData()
val data: LiveData = _data

fun someEvent(foo: Foo) // update _data


class Derived : Base()

class Derived1 : Base()


Then get one of those ViewModels and observe data:



class Frag : Fragment 
onViewCreated()
// get Derived, ViewModelProviders.of ...etc
derived.data.observe // Doesn't observe changes




Calling Base.someEvent(foo) doesn't notify the LiveData in the Fragment.



I want to avoid getting a reference to both subclasses and invoking someEvent on each. One thing to note is that I'm using a single Activity approach and all ViewModels are Activity scoped.










share|improve this question



















  • 1





    The // update _data is kind of the critical piece of code. What exactly are you doing there?

    – ianhanniballake
    Mar 27 at 1:20











  • Please see this stackoverflow.com/questions/56521969/…

    – Levon Petrosyan
    Jun 10 at 16:11

















1















I've tried extracting the value into a base class and having the ViewModels extend it. When I do that, however, the Observer isn't sticking to the LiveData. For instance, when I have a parent class with LiveData:



class Base : ViewModel() 
private val _ data = MutableLiveData()
val data: LiveData = _data

fun someEvent(foo: Foo) // update _data


class Derived : Base()

class Derived1 : Base()


Then get one of those ViewModels and observe data:



class Frag : Fragment 
onViewCreated()
// get Derived, ViewModelProviders.of ...etc
derived.data.observe // Doesn't observe changes




Calling Base.someEvent(foo) doesn't notify the LiveData in the Fragment.



I want to avoid getting a reference to both subclasses and invoking someEvent on each. One thing to note is that I'm using a single Activity approach and all ViewModels are Activity scoped.










share|improve this question



















  • 1





    The // update _data is kind of the critical piece of code. What exactly are you doing there?

    – ianhanniballake
    Mar 27 at 1:20











  • Please see this stackoverflow.com/questions/56521969/…

    – Levon Petrosyan
    Jun 10 at 16:11













1












1








1








I've tried extracting the value into a base class and having the ViewModels extend it. When I do that, however, the Observer isn't sticking to the LiveData. For instance, when I have a parent class with LiveData:



class Base : ViewModel() 
private val _ data = MutableLiveData()
val data: LiveData = _data

fun someEvent(foo: Foo) // update _data


class Derived : Base()

class Derived1 : Base()


Then get one of those ViewModels and observe data:



class Frag : Fragment 
onViewCreated()
// get Derived, ViewModelProviders.of ...etc
derived.data.observe // Doesn't observe changes




Calling Base.someEvent(foo) doesn't notify the LiveData in the Fragment.



I want to avoid getting a reference to both subclasses and invoking someEvent on each. One thing to note is that I'm using a single Activity approach and all ViewModels are Activity scoped.










share|improve this question














I've tried extracting the value into a base class and having the ViewModels extend it. When I do that, however, the Observer isn't sticking to the LiveData. For instance, when I have a parent class with LiveData:



class Base : ViewModel() 
private val _ data = MutableLiveData()
val data: LiveData = _data

fun someEvent(foo: Foo) // update _data


class Derived : Base()

class Derived1 : Base()


Then get one of those ViewModels and observe data:



class Frag : Fragment 
onViewCreated()
// get Derived, ViewModelProviders.of ...etc
derived.data.observe // Doesn't observe changes




Calling Base.someEvent(foo) doesn't notify the LiveData in the Fragment.



I want to avoid getting a reference to both subclasses and invoking someEvent on each. One thing to note is that I'm using a single Activity approach and all ViewModels are Activity scoped.







android kotlin android-architecture-components android-livedata






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 0:34









Jerum Jerum

361 silver badge8 bronze badges




361 silver badge8 bronze badges










  • 1





    The // update _data is kind of the critical piece of code. What exactly are you doing there?

    – ianhanniballake
    Mar 27 at 1:20











  • Please see this stackoverflow.com/questions/56521969/…

    – Levon Petrosyan
    Jun 10 at 16:11












  • 1





    The // update _data is kind of the critical piece of code. What exactly are you doing there?

    – ianhanniballake
    Mar 27 at 1:20











  • Please see this stackoverflow.com/questions/56521969/…

    – Levon Petrosyan
    Jun 10 at 16:11







1




1





The // update _data is kind of the critical piece of code. What exactly are you doing there?

– ianhanniballake
Mar 27 at 1:20





The // update _data is kind of the critical piece of code. What exactly are you doing there?

– ianhanniballake
Mar 27 at 1:20













Please see this stackoverflow.com/questions/56521969/…

– Levon Petrosyan
Jun 10 at 16:11





Please see this stackoverflow.com/questions/56521969/…

– Levon Petrosyan
Jun 10 at 16:11












1 Answer
1






active

oldest

votes


















1














class Derived : Base()


and



class Derived1 : Base()


have their own instance of:



private val _ data = MutableLiveData()
val data: LiveData = _data


that means you need to



derived.data.observe // do something 
derived1.data.observer // do something
derived.someEvent(someFoo)
derived1.someEvent(someFoo)


You are trying to achieve something in a wrong way.






share|improve this answer

























  • I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

    – Jerum
    Mar 27 at 1:34






  • 1





    I don't understand can you explain that further?

    – Archie G. Quiñones
    Mar 27 at 1:56












  • My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

    – Jerum
    Mar 27 at 3:14






  • 1





    then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

    – Archie G. Quiñones
    Mar 27 at 3:58










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%2f55368133%2fhow-can-i-share-livedata-between-multiple-viewmodels%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









1














class Derived : Base()


and



class Derived1 : Base()


have their own instance of:



private val _ data = MutableLiveData()
val data: LiveData = _data


that means you need to



derived.data.observe // do something 
derived1.data.observer // do something
derived.someEvent(someFoo)
derived1.someEvent(someFoo)


You are trying to achieve something in a wrong way.






share|improve this answer

























  • I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

    – Jerum
    Mar 27 at 1:34






  • 1





    I don't understand can you explain that further?

    – Archie G. Quiñones
    Mar 27 at 1:56












  • My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

    – Jerum
    Mar 27 at 3:14






  • 1





    then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

    – Archie G. Quiñones
    Mar 27 at 3:58















1














class Derived : Base()


and



class Derived1 : Base()


have their own instance of:



private val _ data = MutableLiveData()
val data: LiveData = _data


that means you need to



derived.data.observe // do something 
derived1.data.observer // do something
derived.someEvent(someFoo)
derived1.someEvent(someFoo)


You are trying to achieve something in a wrong way.






share|improve this answer

























  • I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

    – Jerum
    Mar 27 at 1:34






  • 1





    I don't understand can you explain that further?

    – Archie G. Quiñones
    Mar 27 at 1:56












  • My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

    – Jerum
    Mar 27 at 3:14






  • 1





    then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

    – Archie G. Quiñones
    Mar 27 at 3:58













1












1








1







class Derived : Base()


and



class Derived1 : Base()


have their own instance of:



private val _ data = MutableLiveData()
val data: LiveData = _data


that means you need to



derived.data.observe // do something 
derived1.data.observer // do something
derived.someEvent(someFoo)
derived1.someEvent(someFoo)


You are trying to achieve something in a wrong way.






share|improve this answer













class Derived : Base()


and



class Derived1 : Base()


have their own instance of:



private val _ data = MutableLiveData()
val data: LiveData = _data


that means you need to



derived.data.observe // do something 
derived1.data.observer // do something
derived.someEvent(someFoo)
derived1.someEvent(someFoo)


You are trying to achieve something in a wrong way.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 1:21









Archie G. QuiñonesArchie G. Quiñones

1,31810 silver badges25 bronze badges




1,31810 silver badges25 bronze badges















  • I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

    – Jerum
    Mar 27 at 1:34






  • 1





    I don't understand can you explain that further?

    – Archie G. Quiñones
    Mar 27 at 1:56












  • My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

    – Jerum
    Mar 27 at 3:14






  • 1





    then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

    – Archie G. Quiñones
    Mar 27 at 3:58

















  • I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

    – Jerum
    Mar 27 at 1:34






  • 1





    I don't understand can you explain that further?

    – Archie G. Quiñones
    Mar 27 at 1:56












  • My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

    – Jerum
    Mar 27 at 3:14






  • 1





    then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

    – Archie G. Quiñones
    Mar 27 at 3:58
















I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

– Jerum
Mar 27 at 1:34





I have a floating action button on multiple(but not all) fragments. It would be ideal to simply dispatch a single click listener with the current location to all relevant fragments instead of setting a click listener for each.

– Jerum
Mar 27 at 1:34




1




1





I don't understand can you explain that further?

– Archie G. Quiñones
Mar 27 at 1:56






I don't understand can you explain that further?

– Archie G. Quiñones
Mar 27 at 1:56














My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

– Jerum
Mar 27 at 3:14





My activity has multiple fragments and some have a FAB. When the FAB is clicked I want some contextual action to occur (will largely be screen dependant but there are other factors too). I feel that doing activity.fab.onclick() in each of those fragments would break encapsulation.

– Jerum
Mar 27 at 3:14




1




1





then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

– Archie G. Quiñones
Mar 27 at 3:58





then delegate the onClick to the Fragments. I dont understand why you can't place the onClick logic inside the fragment.

– Archie G. Quiñones
Mar 27 at 3:58








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















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%2f55368133%2fhow-can-i-share-livedata-between-multiple-viewmodels%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

How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?