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.
Related
I am facing issue that app gets freezed after using it for 3 mins. I am using lifecycleScope.launch {...} to get data from API. I want to know whether i am doing in a right way or not. To do network operations i am using Coroutine lifecycle. Below is my code
lifecycleScope.launch {newAllChatModel.getAllArchivedAPICount()}
Whether i have to cancel all Coroutines on activity onStop if yes then how should i do
viewModelScope.launch(Dispatchers.IO) {
withContext(Dispatchers.Main) {//getting data from server}}
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 have a video playing application. I have implemented Vertical Viewpager2 with fragment. The fragment contains fullscreen exoplayer where I load the video and have a button to open the profile of the user who have posted the video. I make all the API calls in viewmodel as
viewmodelScope.launch(Dispatchers.IO){
... //making api call and updating the livedata
...
}
I am also using
lifecycleScope.launch(Dispatchers.IO){
... //start caching the video
}
The Problem is :
When I scroll like 40 - 45+ items and launch any coroutine on Dispatchers.IO, the launch block is never executed hence the api calls are never made and app stops working.
Debugging results :
I tried to debug why the launch block is not executing with debug break points. In the LimitingDispatcher class, there is variable called inFlightTasks which is used to schedule the task if the parallelism limit is reached (which is 64 by default). So, my current task is added to ConcurrentLinkedQueue<Runnable>. I waited for an hour but after scheduling the task it never resumed the task again. I checked the queue for the tasks and at the time of testing it had around 150-170 tasks but none of them resumed.
Any idea how to solve this problem.
Note : I cannot remove the caching of video(which is am using in onStart() of the fragment).
EDIT
I tried with lifecycleScope.launch{ } and withContext(Dispatchers.IO){ }, but I am still getting the same issue.
In viewModelScope
viewModelScope.launch(Dispatchers.IO){
val response = repository.call()
when(repository){
is Resource.Sucess -> livedata.postValue(response.data)
is Resource.Error -> livedata.postValue(response.error)
}
}
In lifecycleScope
lifecycleScope.launch(Dispatcher.IO){
try{
startVideoCaching()
}catch(e : Exception){
e.printStackTrace()
}
}
And both the functions in launch are purely suspend functions.
Edit 2
I am adding the screen shots of my functions and the Dispatchers.IO's queue data.
Debug sscreenshot.
The functions named in the debug screenshot.
In the sendAnalytics I am using lifecycleScope only
cacheVideo() is called from onStart().
markVideoView() is called from onResume()
I tried with yield() but still no change in the behavior.
I am using all this methods in Fragment which is a part of ViewPager2 items.
If it reached the parallelism limit, and the other ones are put in the queue, the only
logical reason they're not resuming and executing is that those previously called
are not suspending/returning to free up the threads for the queued ones to run.
What you should do is make your functions cancellable (cooperatively cancellable using
isActive) and those coroutines that are fired for the items that are no longer visible
on the screen (scrolled off the screen) should be cancelled, since there is no point of
calculating something not visible on the screen. By cancelling those coroutines you
should always have enough free threads to run those coroutines for the items currently visible on the screen.
In case you don't want to cancel coroutines fired for the items not currently on the screen, you can call yield() inside your functions to deliberately yield thread to other coroutines that run on the same thread pool.
I want user to start some complex background task and observe it's progres and being able to stop it. The process should not stop on screen rotation or application sent to background. The process should stop if user closes an application. The process should stop if user presses appropriate button.
What to use?
Just create a Thread? How would my Activity remember a thread after screen rotate or backgrounded? I can't serialize/parcelalize thread.
Background service? It is said deprecated here: https://developer.android.com/training/run-background-service/create-service
Immediate/Exact/Deferred from here https://developer.android.com/guide/background
But what namely? Diagram infers I should use Deffered, but the name contradicts, because I don't want to defer an execution.
Pls clarify.
We have MvvM architecture to tackle your problem, the ViewModel(A simple java/kt class) will still have its instance when the activity or fragment changes its configurations like(Device rotated, keyboard attached/detached etc). You can run your long task in viewmodel, and listen to the changes in your activity.
Like: ->
MyViewModel.kt
val longWork = MutableLiveData<String>()
fun performLongWork(){
// This is a viewmodel scope, which means,
// if the user has left the UI screen, any work that was started within
// this scope will finish and not report any result. But if you want to
// still continue the work even if the user left the screen,
// use CoroutineScope(IO).launch{}
viewModelScope.launch(Dispatchers.IO) {
//Some looooong task
delay(50000)
longWork.postValue("Completed :)")
}
}
Then in your activity or fragment
private fun observeWork() {
myViewModel.longWork.observe(viewLifecycleOwner, Observer {
it?.let { result ->
// Update the user that the work has completed
myTextView.setText(result)
}
})
}
If you want the work to be completed no matter what, even if the app is closed, or the device is restarted go for the below approach.
Just quoting from Android docs:
WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts.
WorkManagerLink - This will also run immediately if you say it to.
WorkManager.getInstance(context)
.beginWith(workA)
.enqueue()
But if you add constraints like run when the device is charging, then this will obviously defer your execution.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.build()
val myWorkRequest: WorkRequest =
OneTimeWorkRequestBuilder<MyWork>()
.setConstraints(constraints)
.build()
A very good video - Youtube Android Developers - Work Manager
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
}
}