When reading this post about lifecycle-aware CoroutineScope, I read the following:
Every Lifecycle comes with a LifecycleScope, which lets you launch
coroutines that are automatically cancelled once the Lifecycle reaches
the DESTROYED state.
I was reading the source code in lifecycle-runtime-ktx.aar, and was trying to figure out how come the lifecycleScope (accessed within a Fragment or an Activity) can be cancelled when it gets DESTROYED.
Can anyone please point me out why lifecycleScope can be automatically cancelled? And where is the source code about this part. Thanks!
Activity & Fragment internally use the LifecycleCoroutineScope which is then hooked to the Lifecycle of the component via lifecycle.addObserver.
If you check the LifecycleCoroutineScopeImpl,
you'll see this:
if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
coroutineContext.cancel()
}
and
if (lifecycle.currentState <= Lifecycle.State.DESTROYED) {
lifecycle.removeObserver(this)
coroutineContext.cancel()
}
In short,
An observer is added to the component & if the lifecycle.currentState falls below Lifecycle.State.DESTROYED then the running coroutines are cancelled automatically.
Related
I have the following code and a few questions that need to be answered:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleScope.launchWhenResumed {
delay(2000)
Log.d("LifeCycleAware", "launchWhenStarted: before calling")
val result = differentDispatcher()
Log.d("LifeCycleAware", "launchWhenStarted: after calling $result")
}
}
private suspend fun differentDispatcher(): Int =
withContext(Dispatchers.Default) {
for (i in 1..5) {
delay(2000)
Log.d("LifeCycleAware", "Inside different Dispatcher")
}
return#withContext 9
}
override fun onStart() {
super.onStart()
Log.d("LifeCycleAware", "onStart")
}
override fun onStop() {
super.onStop()
Log.d("LifeCycleAware", "onStop")
}
As far as I understand, the method (or any of them) launchWhenResumed, is called when the Lifecycle has reached the RESUMED state, and I also know that when I move the app to the background, the corrutine will stop, but it will not stop if it has child corrutines running in another Dispatcher, so far so good.
So in this code, we determine that if I, in the middle of the loop that is in the differentDispatcher method, send the app to second, it will continue to run but when it finishes, the parent corrutine launched with launchWhenResumed, will not resume until it takes this RESUMED state again.
My first doubt is... if when the corrutine is finished running, I go to the background and return to the foreground, why is it not launched again, if I have returned to the RESUMED state?
I also know about the existence of the repeatOnLifecycle method, where, if I pass the Lifecycle.State.RESUMED state as parameter, it is executed every time, moreover, I know that in this case if I go to the background, the execution of the corrutine is completely suspended and when I go back to the foreground it starts from the beginning, but, why when I run with launchWhenResumed and the corrutine finishes it does not start again, but with repeatOnLifecycle it does? What does it do differently internally?
I guess the answer is because when I switch from background to foreground, the onCreate method is not called again, and I've checked that:
override fun onResume() {
super.onResume()
lifecycleScope.launchWhenResumed {
delay(2000)
Log.d("LifeCycleAware", "launchWhenStarted: before calling")
val result = differentDispatcher()
Log.d("LifeCycleAware", "launchWhenStarted: after calling $result")
}
}
This way it does re-launch because the onResume method does call again when I switch from background to foreground but then.... what kind of magic does the repeatOnLifecycle method do?
The key to understanding launchWhenResumed is to break it down into the two parts that is actually is: a launch and a whenResumed block. Looking at the source code, you'll see it is actually exactly that:
public fun launchWhenResumed(
block: suspend CoroutineScope.() -> Unit
): Job = launch { // It does a regular launch
lifecycle.whenResumed(block) // Then passes your block to whenResumed
}
A launch is a one time operation - a launch done in onCreate() will only run exactly once for each call to onCreate(). This is also why calling launch in onResume() will launch every time you hit onResume.
A call to launch finishes in one of two ways: all of the calls within that block complete normally or the CoroutineScope is cancelled. For lifecycleScope, that cancellation happens when the Lifecycle reaches DESTROYED.
So in a regular launch, work starts immediately, runs until everything completes (or the scope is cancelled), and that's it. It never runs again or restarts at all.
Instead, the whenResumed is an example of Suspend Lifecycle-aware coroutines:
Even though the CoroutineScope provides a proper way to cancel long-running operations automatically, you might have other cases where you want to suspend execution of a code block unless the Lifecycle is in a certain state.
Any coroutine run inside these blocks is suspended if the Lifecycle isn't at least in the minimal desired state.
So what whenResumed does is just pause the coroutine code when you fall below the resumed state, essentially meaning that if your Lifecycle stops being RESUMED, instead of your val result = differentDispatcher() actually resuming execution immediately and your result being delivered back to your code, that result is simply waiting for your Lifecycle to again reach RESUMED.
So whenResumed doesn't have any 'restarting' functionality - just like other coroutine code, it just runs the code you've given it and then completes normally.
You're right that repeatOnLifecycle is a very different pattern. As per the Restartable Lifecycle-aware coroutines, repeatOnLifecycle doesn't have any of the 'pausing' behavior at all:
Even though the lifecycleScope provides a proper way to cancel long-running operations automatically when the Lifecycle is DESTROYED, you might have other cases where you want to start the execution of a code block when the Lifecycle is in a certain state, and cancel when it is in another state.
So in the repeatOnLifecycle call, every time your Lifecycle reaches RESUMED (or what Lifecycle.State you want), the block is ran. When you fall below that state, the whole block is completely cancelled (very similar to when your LifecycleOwner reaches DESTROYED - that level of cancelling the whole coroutine scope).
You'll not the dire warning at the end of the page that talks about both of these APIs:
Warning: Prefer collecting flows using the repeatOnLifecycle API instead of collecting inside the launchWhenX APIs. As the latter APIs suspend the coroutine instead of cancelling it when the Lifecycle is STOPPED, upstream flows are kept active in the background, potentially emitting new items and wasting resources.
The fact that your differentDispatcher code continues to run in the background, despite being inside a whenResumed block is considered a bad thing - if that code was doing more expensive operations, like checking for the user's location (keeping GPS on), it would continue to use up system resources and the user's battery the whole time, even when you aren't RESUMED.
Let's say that we have a simple fragment with a view based on the UI state held in StateFlow in the view model.
On onCreate() we collect state as usually:
override fun onCreate(savedInstanceState: Bundle?) {
lifecycleScope.launchWhenStarted {
viewModel.uiState.collect {
// UI update according to state
}
}
}
Now we navigate to the next fragment - the previous is kept by the fragment manager, but the view is destroyed. On the new fragment, we pop back stack and now is surprising:
the previous fragment is recreating the view on the initial state and even if we try to update state flow nothing will happen since it doesn't emit equal data twice one by one.
So, how to restore the view state after return to the fragment?
Maybe a bit later but what you are looking for is repeatOnLifeCycle
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect { ... }
}
}
repeatOnLifecycle together with lifecycleScope.launch allows you to collect flows from a Fragment or Activity.
The main difference with your approach is that launchWhenStarted will run you collection function ONCE the UI State is started, but will not repeat the collection when a fragment is restored, while repeatOnLifeCycle will create a new coroutine starting the collection everytime the lifecycle scope reaches the specified state (hence the name) and will cancel it when the lifecycle reaches the opposite state (for example, if you specified STARTED, then the coroutine will be cancelled on onStop).
In addition to that, the launchWhenX documentation nowadays indicates the following
Caution: This API is not recommended to use as it can lead to wasted
resources in some cases. Please, use the Lifecycle.repeatOnLifecycle
API instead. This API will be removed in a future release.
PD, lifecycleScope.launch { ... } creates a coroutine, and is required as repeatOnLifecycle is a suspend function (suspend functions run on a coroutine or another suspend function)
I am having this interesting problem. I need to do some work immediately after insertion, but viewModelScope randomly, or at least it looks like randomly, skips functions except for the first one.
Example:
fun insertItem(item: SingleItem) = viewModelScope.launch {
itemsRepository.insertItem(item)
increaseAmount(item.catId)
}
So in this example everything runs ok only after fresh app install, but then on the next app launches second function "increaseAmount" will be randomly skipped and i don`t know why.
And it doesn't matter what goes after first function. I tried simple "Log" and it gets skipped as well. Is it normal for viewModelScope?
EDIT
Checked for exceptions. Second function throws an exception that the job was cancelled:
kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelling}#2d87ff
Also, in my Fragment it is called like this:
viewModel.insertItem(newItem)
root.findNavController().popBackStack()
So after calling this function i go back to previous Fragment. Is it possible that viewModel gets destroyed before it finishes executing all work?
Is it normal for viewModelScope?
No, it is not. In coroutines functions call must be sequential. Functions itemsRepository.insertItem(item) and increaseAmount(item.catId) must be called one after another. I see a couple of reasons why second function is not called:
Function itemsRepository.insertItem(item) throws some exception.
Current coroutine scope is cancelled before second function call.
Edit:
ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel. The ViewModel remains in memory until the Lifecycle it's scoped to goes away permanently: in the case of an activity, when it finishes, while in the case of a fragment, when it's detached.
After you call root.findNavController().popBackStack() your fragment will be detached, the ViewModel cleared and coroutine job cancelled.
You can initialize the ViewModel in the fragment in the following way:
private val viewModel: YourViewModel by activityViewModels()
Initializing viewModel in this way it will be scoped to the Lifecycle of an Activity.
To use activityViewModels() add next line to the dependencies of app's build.gradle file:
implementation "androidx.fragment:fragment-ktx:1.2.5"
Does that make sense to launch operations, like db writes, that needs to continue after the fragment lifecycle?
Code sample:
requireActivity().lifecycleScope.launch {
// suspend function invocation
}
MainScope().launch {
// suspend function invocation
}
The most important difference between MainScope and lifecycleScope is in the cancellation management of the launched coroutine.
I know your question is about requireActivity().lifecycleScope, but let me do it step by step.
With lifecycleScope, cancellation is done for you automatically - in the onDestroy() event in either Fragment or Activity, depending on whose lifecycle your hooked into.
With the mainScope, you’re on your own, and would have to add the scope.cancel() yourself, like below:
class MyActivity: Activity {
private val scope = MainScope()
// launch a coroutine on this scope in onViewCreated
override fun onDestroy() {
super.onDestroy()
//you have to add this manually
scope.cancel()
}
}
More info at:
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-scope.html
In other words, what you do (or supposed to do) manually with main scope, lifecycleScope does it for you automatically.
Now, at this point, you could (maybe) say, aha - it is the main Scope that I want, because my operation is not automatically cancelled, it’s exactly what I want, so i can just skip adding the cancellation call.
In a way, yes, you will get what you wish, as indeed it will keep running for some indeterminate perid of time until the Fragment and its variables are garbage collected, but you will no longer have access to that scope - the fragment is gone, and when you navigate into the fragment again, a new instance is going to be created, along with a new main scope. And of course you have no guarantee on how long it is going to be before the garbage collection kicks in. And what about exceptions?
Now on to requireActivity().lifecycleScope.
If you use requireActivity().lifeCycleScope, you obviously jump on the Activity lifecycle and get two advantages - a longer life cycle (presumably, there are other fragments in the activity, and say navigation back from the fragment in question just navigates to another fragment within the same activity, and not exits the app), and automatic cancellation in OnDestroy().
That may be enough. But a) your job handle, if you need one, will still stay in the fragment, and yet again, once you lose the fragment, you no longer have access to the job (assuming you need it), and b) your activity will not survive a configuration change (unless you expressly prohibit them). If you want to allow and handle configuration changes, go with the viewModelScope on the activity (and use a shared view model between activity and fragment).
The ViewModel class allows data to survive configuration changes such as screen rotations.
And, finally, if none of that is enough (your “Db save” operation is taking a really long time), use a Service (or WorkManager, etc). But at that point, the proper question to ask will be “why is it taking so long?” and focus on that.
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
}
}