https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Nikola Milovic

04/09/2021, 9:01 AM
Hey guys, where can I read more about this kind of behaviour?
Copy code
fun A() {
B()
C()
}

fun B(){
  scope.launch{
  //call some suspending fun
   }
}
So now C will be executed before B finishes even tho B isn't suspending fun?
I need it for an actual usecase. I want to save the progress the user has made before navigating to another screen
Copy code
binding.exitButton.setOnClickListener {
            autoSave() 
            viewModel.navigateToMainMenu()      
        }
Navigate is a regular function while
Copy code
fun autoSave() {
        uiScope.launch{
            viewModel.autoSave()
        }
    }
viewModel.autosave is a suspending fun. Now I need it to first save and then proceed to navigate. As now it's not happening in that order
m

Marko Novakovic

04/09/2021, 9:08 AM
@Nikola Milovic why calling
uiScope.launch {}
in order to call
viewModel.autoSave()
?
everything should go through
ViewModel
and then you won’t have this kind of problems
now, as I can see, you depend on race conditions
make
ViewModel
start a coroutine and when saving work is done emit event to navigate to main menu
n

Nikola Milovic

04/09/2021, 9:12 AM
Thank you @Marko Novakovic
m

Marko Novakovic

04/09/2021, 9:13 AM
@Nikola Milovic you’re welcome
u

uli

04/09/2021, 11:41 AM
No need for events:
Copy code
binding.exitButton.setOnClickListener {
            uiScope.launch{
                autoSave() 
                viewModel.navigateToMainMenu()
            }     
        }
Copy code
suspend fun autoSave() {
        viewModel.autoSave()
    }
And depending on the rest of your code you can remove autoSave() (inline it)
Copy code
binding.exitButton.setOnClickListener {
            uiScope.launch{
                viewModel.autoSave() 
                viewModel.navigateToMainMenu()
            }     
        }
m

Marko Novakovic

04/09/2021, 12:39 PM
More of a workaround than a proper solution
u

uli

04/09/2021, 2:57 PM
why would you say that. That’s what coroutines are for. making asynchronous flows linear. Of cause you might want to move the responsibility to the view model.