How to wait for suspend function or a query to complete inside viewModelScope.launch {}

I searched for this on SO and think i have got the answer.

Consider the below code in your viewmodel:


viewModelScope.launch{
    db.userProfileDatabaseDao.logout ()
    println("here")
}

will "here" be printed after the logout function in the Dao completes?

The answer is yes. everything within launch is part of a coroutine and will be executed sequentially. if logout () does not execute and here is printed - it means something is amiss with the logout function.

So if "here" is printed but the logout () is not executed - you should enclose the db.userProfileDatabaseDao.logout () within a try-catch block. print e.message in the catch block to see why the logout function failed.

if you wish to execute two tasks in parallel - you can do it as below :



viewModelScope.launch{
    launch{
        task1 ()
    }
        launch{
        task2 ()
    }
}

now task1 () and task2() will execute in parallel.

If you find any mistakes in this post or if you have queries - please hit comment.

I am @mrtechmaker on twitter - lets stay in touch as we make android apps. Peace. Cheers.