'How to check if a suspend function has completed executing
Hello I have a suspend function updateUserWithNewPersonalDetails(), I want check if the function has been executed and once executed I want to call success() function.
I am unable to use invokeOnCompletion on the function call
How can I do this please or what is the other way I can call success() function once updateUserWithNewPersonalDetails is executed
suspend function
suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
userDao.get().collect { cachedUser ->
val updatedCachedUser = UserDB(cachedUser.id, ...)
userDao.save(updatedCachedUser)
}
}
from viewmodel I want to call the above function and on success or invoke successfull I want to call success function
userRepo.updateUserWithNewPersonalDetails(details). invokeOnCompletion{
success()
}
Thanks R
Solution 1:[1]
Currently your function updateUserWithNewPersonalDetails never completes because the Flow returned by Room never completes (it monitors for DB changes forever).
Assuming you are interested only in the first change you can do:
suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
val cachedUSer = userDao.get().first() // this will get the current value from the DB
val updatedCachedUser = UserDB(cachedUser.id, ...)
userDao.save(updatedCachedUser)
}
Here first() gets the current value from the DB (or throws if it doesn't exist) and does NOT observe forever. Alternatively you can use firstOrNull().
Then your other function becomes:
updateUserWithNewPersonalDetails()
success()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LordRaydenMK |
