Referring to your first example which is explaining the use ofSupervisorJob()
, any particular reason to not usesupervisorScope { }
? I can use some advice on validating if I am using it in the right way.
I have this Service in my Android project.
class DummyService : CoroutineScope {override val coroutineContext: CoroutineContext = Dispatchers.IO
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//ignoring other code
parentJob = launch { manager.handleStuffAsync() }
parentJob?.invokeOnCompletion { error: Throwable? ->
logger.d(“invokeOnCompletion reached..”)
}
}
}
In the Manager class, I am basically creating the child jobs which should run asynchronously and even if one of them fails the whole flow should run fine. Also, I have setup a timeout.
class Manager {suspend fun handleStuffAsync() = supervisorScope {val task1 = async { loadTask1() } //loadTask1() is a suspend function
val task2 = async { loadTask2() } //loadTask2() is a suspend functionwithTimeoutOrNull(10000) {
try {
val resultTask1 = task1.await()
} catch (e: Exception) {
logger.e(“Inside Handler Caught $e”)
}
}withTimeoutOrNull(10000) {
try {
val resultTask2 = task2.await()
} catch (e: Exception) {
logger.e(“Inside Handler Caught $e”)
}
}
}
} //supervisorScope ends here
It kind of serves the purpose. If any exception occurs in task1 or task2 due to TimeOut or internal working then still the whole flow completes.
Is there anything which I can improve or doing it wrong?