I am trying to run a function called getGroupSummaries and have it finish before the next code runs. getGroupSummaries is declared like this:
suspend fun getGroupSummaries(groupInfo: GroupInformation, adminUserInfo:
UserInformation){
and it is invoked like this:
runBlocking {
val getGroupSummariesJob = viewModelScope.launch {
getGroupSummaries(groupInformation, userInformation)
}
getGroupSummariesJob.join()
}
Timber.e("After getGroupSummaries, groupInformationList size = " + groupInformationList.size)
This logging message says that the size of groupInformationList is 0. Inside getGroupSummaries I have a logging message that prints out the size of groupInformationList, and the size is 1.
The first logging message, which is supposed to display after getGroupSummaries ends, displays before the second one, which is inside getGroupSummaries. This says that the blocking is not working properly. I am new to this syntax and would appreciate any advice.
In making a minimal reproducible example, I removed a loop and then the example worked correctly. Thank you for the suggestion to do this.
If you launch with some other scope (like
viewModelScope), runBlocking won’t wait for it. You would need to launch with runBlocking’s own scope that is provided as the receiver of its lambda, so just use a barelaunch. Except, if you just want to wait for a simple suspend function call (no parallelism), you shouldn’t be launching anything. Just directly call the suspend function insiderunBlocking.Make sure you aren’t using
runBlockingon the main thread! Using it for anything besides linking coroutine code with legacy non-coroutine multi-threaded code is a code smell. Coroutines eliminate the need to block to wait for things so your use in your example is very suspicious. This might be an A-B problem.