Android MediatorLiveData observer -


i'm bit confused on why following code doesn't work:

mutablelivedata<string> mutabletest = new mutablelivedata<>(); mediatorlivedata<string> mediatortest = new mediatorlivedata<>(); mediatortest.addsource(mutabletest, test -> {     timber.d(test); }); mutabletest.setvalue("bla!"); 

this code seems straightforward, debugger doesn't enter callback , nothing logged console...

edit: shouldn't work then?

    mutablelivedata<string> mutabletest = new mutablelivedata<>();     mediatorlivedata<string> mediatortest = new mediatorlivedata<>();     mediatortest.observe(loginactivity, str -> timber.d(str));     mediatortest.addsource(mutabletest, str -> timber.d(str));     mutabletest.setvalue("bla!"); 

this answer largely reproduction of @commonsware has shared in comment section above.

in order callback on mediatorlivedata's addsource method triggered, mediatorlivedata object needs observed well.

the logic behind 'mediator' mediates between livedata object observes, , final consumer of data. mediator hence observer , observable simultaneously, , callback on addsource won't triggered mediator when there no active observers.

as example; according google's android architecture components, activity or fragment have observer observing mediator on viewmodel, in turn may observe other livedata objects handled within viewmodel or referenced utility class.

@commonsware pointed out use of transformation class exposes methods map , switchmap, these not within scope of use case although worth checking out.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -