I am having issues with LiveData.
I have 3 fragments A (menuFragment), B (doThingsFragment), C (displayMessageFragment).
We can move from A to B, from B to C and finally from C to A.
On the onStart method of doThingsFragment, I observe LiveData From doThingsViewModel and I move to displayMessageFragment when this value changes.
doThingsViewModel :
private var _message : MutableLiveData<String> = MutableLiveData()
var message : LiveData<String> = _message
fun someFunction() {
_message.value = "blablabla"
}
doThingsFragment :
override fun onStart() {
super.onStart()
mViewModel!!.message.observe(
viewLifecycleOwner,
Observer<String>
{
msg ->
if(!msg.isNullOrEmpty() && mViewModel!!.toastType.value != null){
val args = Bundle()
args.putString("message", msg)
Navigation.findNavController(requireView()).navigate(R.id.mountUnmountValidationFragment, args)
}
})
}
It works great the first time I update _message (we go from B to C as expected).
However, when I try to move from A to B again, we go into doThingsFragment observer callback again and I move on to fragment C before fragment B is even displayed.
Since _message value has not changed, I expect not to trigger the observer callback everytime doThingFragment.onStart method is called...
What am I missing ?
Thanks a lot !
It is the way how livedata behave, if you need receiver event only one time, google or stackoverflow about SingleLiveData
LiveData works on an Observer pattern, where something registers as an observer, and every time the thing it's observing changes, it gets notified. It's worth reading the docs on this:
Adds the given observer to the observers list within the lifespan of the given owner. The events are dispatched on the main thread. If LiveData already has data set, it will be delivered to the observer.
When data changes while the owner [LifecycleOwner, e.g. the Activity] is not active, it will not receive any updates. If it becomes active again, it will receive the last available data automatically.
These are the important points - when you register to observe the data, you'll immediately be notified of the most recent value (if there is one), not just when there's a change. So you can't rely on that callback triggering as a signal that you need to move from B to C.
What you actually need to do depends on your app logic, how you can tell the difference between "fragment B just displayed, here's a value, and now I need to show fragment C" and "fragment B just displayed, here's a value, but I happen to know I don't need to show fragment C this time". You could do things with setting an initialised flag the first time you receive some data (might need to persist that state in onSaveInstanceState) or holding the last-seen value (harder to persist) but you get the idea
Related
I am reading LiveData source code, and for this method:
public void observe(#NonNull LifecycleOwner owner, #NonNull Observer<?super T> observer) { .. }
And this is part of its doc:
When data changes while the owner is not active, it will not receive
any updates. If it becomes active again, it will receive the last
available data automatically.
I was trying to figure out why LiveData can achieve this lifecycle-awareness. I read source code of setValue but still couldn't get it. Can anybody help me with the on the general idea?
Suppose you are not using live data and you are showing list of data with pagination concept . You as user have scroll down to view more and more data and application is calling apis to get data as you scroll . Now you have rotated your device so as developer we know that your activity will be recreated and user will be at initial stage again as all things were destroyed .. Well you can achieve this using onSaveInstance but you will have to code and manage yourself ..
So user will have to scroll again to view all data but imagine if you have some mechanism where you get your last updated data whenever activity lifecycle changes so you can easily set data again and allow user to use your app like nothing happened .. and here livedata concept come into picture with lifecycle awareness
Hope this answer will clear your doubts
Edit :-
To understand how they are managing lifecycle , you can visit this link
https://developer.android.com/topic/libraries/architecture/lifecycle#lc
here is source code method of LiveData class where you can see(at last line) how they are adding lifecycler owne to observer
Read the source code of LiveData.java (in lifecycle-livedata-core:2.2.0#aar) again, it seems clear to me now.
When adding an observer to LiveData via liveData.observe(lifecycleOwner, Observer { .. } ), the magic happens in the observe method.
In the observe method, it puts the lifecycleOwner and the Observer into a new object called LifecycleBoundObserver like this:
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
// ... some other code
owner.getLifecycle().addObserver(wrapper);
Important to note and we can also tell it from the last statement: the LifecycleBoundObserver is an instance of LifecycleObserver, that means, it can be notified when the given lifecycleOwner gets state updated, the key lies in the onStateChanged method of LifecycleBoundObserver.
#Override
public void onStateChanged(#NonNull LifecycleOwner source,
#NonNull Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}
So:
If the lifecycleOwner (the Activity or Fragment) gets DESTROYED, it will remove the observer (the callback observer, not the LifecycleObserver), hence the observer won't be notified for new data once it's DESTROYED.
If it is not DESTROYED, it requires the lifecycleOwner in Active states (STARTED or RESUMED), this is restricted by the return value from the method shouldBeAlive(), and finally the new data gets delivered to observer callback in the method activeStateChanged.
void activeStateChanged(boolean newActive) {
if (newActive == mActive) {
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
boolean wasInactive = LiveData.this.mActiveCount == 0;
LiveData.this.mActiveCount += mActive ? 1 : -1;
if (wasInactive && mActive) {
onActive();
}
if (LiveData.this.mActiveCount == 0 && !mActive) {
onInactive();
}
if (mActive) {
dispatchingValue(this);
}
}
If the input param newActive is true, then finally it will reach the statement of dispatchingValue(this) - the last statement, and if it is false (i.e.: inactive states: PAUSED / STOPPED / DESTROYED), it won't call dispatchingValue(this), thus the observer callback won't be triggered.
If the Activity / Fragment goes back to foreground from background, it becomes Active again, then the LifecycleBoundObserver will be notified and the onStateChanged will be called again, and this time, when calling activeStateChanged(newActive), it passes true, therefore, dispatchingValue(this) will be called, and the latest data set via setValue or post will be picked up, that's the reason for explaining why the Activity can get the last emitted / latest value of LiveData.
In MyViewModel a MutableStateFlow is used to transmit events to the fragment.
When the value of the MutableStateFlow is changed the earlier values are being overwritten inside the coroutine. So never received by fragment.
internal class MyViewModel(application: Application) : AndroidViewModel(application) {
private val myMutableStateFlow = MutableStateFlow<MySealedClass>(MySealedClass.Dummy1())
private fun getData() {
viewModelScope.launch {
//yield()
myMutableStateFlow.value = MySealedClass.Dummy2()
myMutableStateFlow.value = MySealedClass.Dummy3()
}
}
}
internal class MyFragment : Fragment(){
private var uiStateJob: Job? = null
override fun onStart() {
super.onStart()
uiStateJob = lifecycleScope.launch {
myViewModel.getUiFlow().collect {
//do something
}
}
}
}
If yield() is commented Dummy2 event is never received by the Fragment. Dummy 3 is received though.
If yield() is uncommented Dummy2 & 3 are both received.
If the state values are changed outside the coroutine then both Dummy2 and Dummy3 are received.
I need to predictably receive all events in my fragment.
Is there a proper reasoning for this behaviour?
StateFlow is meant to represent a state. Each event is technically a new up-to-date state value, making the previous states obsolete. This type of flow is for situations when only the latest state matters, because its events are conflated. From the docs:
Updates to the value are always conflated. So a slow collector skips fast updates, but always collects the most recently emitted value.
Edit in response to your comment: yield() is a suspend function that forces the suspension of the current coroutine. Therefore it gives a chance to the other coroutine to progress until its next suspension point, this is why in that case the collect is "ready" before the first value is set (and emitted).
However you shouldn't rely on that because it's brittle: if the other coroutine gets modified and has extra suspension points by calling other suspend functions, it might not reach the collect call, and you would be back to the other behaviour.
If you consistently need all events, you have several options:
Switch to a cold flow, which will only start when you collect
Use a Channel (with or without buffer)
Use a SharedFlow and trigger the events start by using onSubscription
Reading the LiveData documentation found here, I came across this section:
If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.
When I create a blank project to test this, I discover that latest data is not dispatched when coming from background.
Sample code from onCreate():
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
button.setOnClickListener {
viewModel.buttonClicked()
}
viewModel.textLiveData.observe(this, Observer {
textview.text = it
Log.d("TEST", "new data = $it")
})
When going to background and coming back, should the latest data that the LiveData is holding be dispatched again to the observer?
UPDATE:
ViewModel code as requested:
class MyViewModel : ViewModel() {
val textLiveData = MutableLiveData<String>()
fun buttonClicked() {
textLiveData.value = "new text value"
}
}
So, after a lot of investigation, I will share my answer using two scenarios to make it easier to grasp
Scenario 1:
App is in foreground
Observer receives latest data change from LiveData
App goes to background
When coming back from background, LiveData will NOT dispatch the value since the Observer already consumed/has the latest change.
Scenario 2:
App is in foreground
Observer receives latest data change from LiveData
App goes to background.
While App is in background, LiveData receives a new value.
Since App is still in background and Observer is not in an active state, LiveData will not dispatch the value change yet.
When coming back to foreground and Observer is in an active state again, LiveData does dispatch the latest value since it has changed
I'm working on small android app using MVVM pattern.
My issue is that my ViewModel observer in MyActivity not called from the background. I need it to be called even if the app is in background to show system Notification to the user that app calculation process is done and the result is ready.
This is the current implementation located in onCreate in MyActivity:
mainActivityViewModel.getTestResult().observe(MainActivity.this, new Observer<String>() {
#Override
public void onChanged(#Nullable String blogList) {
Toast.makeText(getApplicationContext(), "test...", Toast.LENGTH_SHORT).show();
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)){
//The app is in foreground - showDialog
}else{
//The app is in background - showNotification
}
}
For now, this observer will be called only if the app is in foreground - if the process done while app was in foreground - 'showDialog' will trigger, if the app was in background - the showNotification will trigger - but only after I will open the app again. It's not the behaviour that I try to achieve. Please help! Thanks.
onChanged will only be called if the Activity's current Lifecycle state is at least STARTED. onPause gets called when you leave the Activity, which means it's not at least STARTED.
LiveData is simply not suitable for the behavior you're trying to achieve.
I would recommend you to use a foreground Service instead. Especially if the mentioned "calculation process" is something that the user should be aware of.
edit:
Let's say you're performing some potentially long running task in the background and you want to continue this task even if the user would leave or even close your Activity. Then using a Service is a good option, and especially a foreground Service if the task is the result of a user action. For example, the user clicks an "upload" button, a foreground Service performs the task and the associated Notification says "Upload in progress".
You have the option to either
Always show a new Notification when the task is complete, regardless of if the Activity is shown or not. This is pretty common.
Only show the Notification if the Activity is not currently started, and if it is started, show something in the Activity view instead.
In order to do the latter option, you need to know the current status of the Activity's Lifecycle. You want to be able to do the following check from your service somehow: getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
The best way to communicate between an Activity and Service is binding to the Service and extending the Binder class in the Service.
After binding, you may store the Activity Lifecycle status in a variable in the Service, or even provide the Activity itself to the Service.
I guess your getTestResult() in ViewModel returning some live data.
So first of all, you are assigning your real data with LiveData using .setValue(some_data) method. And it is working fine while app is open. Btu when your app is in background. You need to use .postValue(some_data) method to assign data with that LiveData.
Check difference below:
setValue()
Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.
postValue()
Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.
Conclusion, the key difference would be:
setValue() method must be called from the main thread. But if you need set a value from a background thread, postValue() should be used.
I saw this question researching for the same issue and even though it was asked 2 years ago I was able to let LiveData notify the observer even though the Fragment (or in question's case, an Activity) is either paused or stopped, so I am posting my solution here.
The solution is for a fragment, but can be adapted to activities as well.
On the fragment:
class MyFragment: Fragment() {
private var _lifecycleWrapper: LifecycleOwnerWrapper? = null
val activeLifecycleOwner: LifecycleOwner
get() {
if (_lifecycleWrapper == null)
_lifecycleWrapper = LifecycleOwnerWrapper(viewLifecycleOwner)
return _lifecycleWrapper!!
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
// On the livedata, use "activeLifecycleOwner"
// instead of "viewLifecycleOwner"
myLiveData.observe(activeLifecycleOwner) { value ->
// do processing even when in background
}
}
override fun onDestroyView() {
super.onDestroyView()
_lifecycleWrapper = null
}
}
LifecycleOwnerWrapper:
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
/**
* A special lifecycle owner that lets the livedata
* post values even though the source lifecycle owner is in paused or stopped
* state. It gets destroyed when the source lifecycle owner gets destroyed.
*/
class LifecycleOwnerWrapper(sourceOwner: LifecycleOwner):
LifecycleOwner, LifecycleEventObserver
{
private val lifecycle = LifecycleRegistry(this)
init
{
sourceOwner.lifecycle.addObserver(this)
when (sourceOwner.lifecycle.currentState)
{
Lifecycle.State.DESTROYED -> lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
Lifecycle.State.CREATED -> lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
Lifecycle.State.STARTED -> lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START)
Lifecycle.State.RESUMED -> lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
else ->
{
// do nothing, the observer will catch up
}
}
}
override fun getLifecycle(): Lifecycle
{
return lifecycle
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
{
if (event != Lifecycle.Event.ON_PAUSE && event != Lifecycle.Event.ON_STOP)
lifecycle.handleLifecycleEvent(event)
}
}
The only thing you need to do is to not call this after onDestroy (or for viewLifecycleOwner, after onDestroyView) otherwise the lifecycle owner will be stale.
What you are trying to do is possible but not in the way you are doing it.
The whole purpose of the LiveData API is to link the data layer with the UI in a life cycle aware manner, so when the app is not in foreground then the observer knows that and stop updating the UI.
The first argument on the observer is the lifecycle.
This is a great improvement because without it the crashes because UI was not available were too often or it was too complex to control manually (boilerplate, edge cases, etc).
Service is not a good idea because the services can be killed by the DALVIK or ANT machine if the memory is needed for the foreground app. Services are not in the foreground but that doesn't mean that are bound to background neither that are guaranteed to be working for a undeterminated span of time.
For doing what you wish use the WorkManager. The WorkManager allows you to schedule jobs with or without conditions and from there you are gonna be able to send a Notification to the user.
You can try for a combination of Workmanager and Viewmodel to achieve an foreground/background app functionality.
For this use the Activity life cycle:
Use the onResume method to remove any WorkManager and star using the ViewModel
Use the onPause method to star the WorkManager
To handle the declaration, you can edit or dismiss the declaration from inside the function in your ViewModel class where the data was successfully retrieved.
private fun dataShow(list: List<String>) {
//Notification cancel
NotificationManagerCompat.from(getApplication()).cancel(30)
if (list.isNotEmpty()) {
data.value = list
progressHome.value = false
} else {
progressHome.value = true
}
}
Mutable LiveData in a ViewModel:
val viewStateLiveData: MutableLiveData<SomeViewState> = MutableLiveData()
When a network call fails, this function (in the ViewModel) is called from the main thread to update the view state object (to display a Snackbar, but then reset the state so it isn't re-displayed):
#UiThread
private fun onFailure() {
viewStateLiveData.value = viewStateLiveData.value?.copy(retrievalSuccess = false, showProgress = false)
viewStateLiveData.value = viewStateLiveData.value?.copy(retrievalSuccess = null)
}
The Fragment observes the MutableLiveData:
viewModel.viewStateLiveData.observe(this, Observer { viewState ->
Timber.i("Update ViewState: $viewState")
})
But the output is this single observer call (representing the second mutation):
Update ViewState: ViewState(retrievalSuccess=null, showProgress=false)
Rather than what I would expect, which would be two calls to the observer, reflecting both mutations:
Update ViewState: ViewState(retrievalSuccess=false, showProgress=false)
Update ViewState: ViewState(retrievalSuccess=null, showProgress=false)
Why is MutableLiveData.setValue() not triggering the observer after both mutations? The docs say "Sets the value. If there are active observers, the value will be dispatched to them." but it's hard not to conclude that this is not the case as setValue() is being called, but the observer (which is active) is not being triggered. The observer is definitely set up in advance of the MutableLiveData mutations.
I experimented with a series of mutations, and only ever see one call to the observer, which receives a view state object that combines all the prior mutations. So the calls to setValue() are mutating the view state, but only the last call in a series is triggering the observer.
I tried using postValue() in vain. Oddly, this behavior I'm describing was not present until recently, but it's not clear what has changed that has caused these issues.
This was a Fragment lifecycle/timing issue, and ultimately caused by the ViewState mutations happening before the Fragment was in the active state, and so the LiveData just received a single event when the Fragment reached the Active, representing all mutations up to that point in a single initial event.
To fix it these changes were made:
onCreate() - create ViewModel
onViewCreated() - start observing the LiveData
onResume() / onStart() - make the network request (which starts the flow of mutated view states)
In debugging this issue it was really helpful to add logging to this, to see what state the Fragment was in: fragmentManager?.registerFragmentLifecycleCallbacks(...)