how to return a boolean after completion of coroutine?

1.4k views Asked by At

I have a Boolean method inside that some nested method, I want to return that boolean value after completion of all methods but it first executes that boolean value and returns that. It prints->Entered, completed and started, end.

  fun syncAll(): Boolean {
 
    Log.d(TAG, "syncAll: Entered")
   val job= Coroutines.io {
        Log.d(TAG, "syncAll: started")
        method1()
        method2()
        method3()
        Log.d(TAG, "syncAll: end")
    }
    Log.d(TAG, "syncAll: completed")

    return job.isCompleted
}
2

There are 2 answers

2
Nikola Despotoski On

You need to make syncAll() suspend function and call it from CoroutineScope that is at the calling site.

Inside syncAll() you can use withContext() to await result from different methods running on different coroutine(s).

0
Ehsan msz On

syncAll should be a suspend function:

suspend fun syncAll(): Boolean {
    println("sync: started")
    val job = Job()
    CoroutineScope(Dispatchers.IO + job).launch {
        delayFunction(1000)
        delayFunction(2000)
        delayFunction(3000)
        println("sync: end")
    }.join() //Suspends the coroutine until this job is complete
    println("sync: completed")
    return job.complete()
}

suspend fun delayFunction(d: Long) {
    delay(d)
}

you have to call this function inside a coroutine:

val job = Job()
CoroutineScope(Dispatchers.Main + job).launch {
    val result = syncAll()
    println("sync: finished: $result")
}

result:

sync: started
sync: end //after 6 seconds
sync: completed
sync: finished: true