In Kotlin code, runBlocking does not block

55 Views Asked by At

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.

1

There are 1 best solutions below

0
Tenfour04 On

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 bare launch. 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 inside runBlocking.

Make sure you aren’t using runBlocking on 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.