Hey! :wave: I have the following (simplified) code...
# coroutines
e
Hey! đź‘‹ I have the following (simplified) code:
Copy code
fun addItem(item: String) {
    viewModelScope.launch {
        repository.saveDataInRoom(item)
        interactor.sendNotification(item)
        interactor2.updateWidget(item)
    }
}
The “addItem” screen is a Bottom Sheet that is dismissed after the user adds an item. Since the
saveDataInRoom()
is a heavy operation, by the time it ends the execution the coroutine was already cancelled by passing on
ViewModel#onCleared()
. Then no code after that is executed after that command. Any suggestions on how to ensure that everything is executed? Thanks!
k
Don't dismiss the bottom sheet immediately after the item is added, instead trigger an animation so you show some progress and after your data is saved you can safely dismiss the bottom sheet, that's how I'd do it.
j
or use another scope, activity/app
e
The idea would be basically creating a scope and injecting it into the ViewModel? But how would I cancel/clear that scope?
k
You have to scope it to another part of your app, one potential good scope could be the immediate parent of the bottom sheet
j
i think it is easier to use
suspend fun addItem
and call it with an activity lifecycle scope
a
This post gives some good examples on how to handle coroutines that should outlive/not be cancelled with their current scopes: https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad - like Kevin said, basically inject the scope into the view model and let it clear itself when necessary. Having said that, is the updated widget in the bottom sheet or in the parent? If it's in the later, maybe you should move the code to update the widget/show the notification to the parent itself
e
Thanks a lot!
j
You can create a SupervisorScope (like viewModelScope) and inject it on your repository. Don`t worry about cancelation, coroutines are cancelled after finish, and if you want to cancel it manually, you can create a function specifically to it.