0

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
  • 1
    Are we supposed to guess on what groupInformationList is? Commented Jan 29, 2024 at 19:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.