• 12

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

private val coroutineSupervisor = SupervisorJob()
protected val dispatcherProvider = CoroutineDispatcherProvider()
protected val viewModelScope = CoroutineScope(dispatcherProvider.main + coroutineSupervisor)

class CoroutineDispatcherProvider {

    val main: CoroutineDispatcher
        get() = Dispatchers.Main

    val background: CoroutineDispatcher
        get() = Dispatchers.IO

viewModelScope.launch {
    runBlocking {
        async { firstNumber() }.await()
        async { secondNumber() }.await()
        async { test() }.await()
        async { thirdNumber() }.await()

suspend fun firstNumber(): Int {
    delay(3_000) // 3 seconds delay
    return 5
suspend fun secondNumber(): Int {
    delay(5_000) // 5 seconds delay
    return 8
suspend fun thirdNumber(): Int {
    delay(7_000) // 7 seconds delay
    return 10

suspend fun test() {
    withContext(dispatcherProvider.background) {

Started learning coroutines few days ago and I saw something weird. firstNumber, secondNumber and thirdNumber function run as they should - delay is done and then the next function executes - in the right sequence, but test() does not. It returns value a lot later and runBlocking is already done when that happens. I would like to make sure, that it gets result and then somehow use it in other request. Is it because I'm using some kind of wrong dispatcher there or what?

Here is the thing. What you are expecting when you call test() method through async and await is to wait it till completes.

But As you have a callback flow(apiclient call) inside the test method, it returns immediately before getting response from server and exits the test method. Later Callback lambda is called when the response is ready. By this time run blocking is already done.

So You should do is to convert your callback into Coroutine. Codelabs-example

And you can create a list of Deferred objects out of the api call and await on each one.

  • 1
Reply Report