https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Joe

02/05/2020, 7:41 PM
What is generally stylistically preferred:
Copy code
class CoroutineJob {
    suspend fun doWork() {
          // do stuff in coroutine context
    }
}
// elsewhere:
scope.launch { 
    CoroutineJob().doWork()
)
or
Copy code
class CoroutineJob(val scope: CoroutineScope) {
    fun launchWork() {
        scope.launch {
            // do stuff in coroutine context (possibly calling another suspend fun member?)
        }
    }
}
// elsewhere:
CoroutineJob(scope).launchWork()
or something else?
1️⃣ 9
b

bdawg.io

02/05/2020, 8:34 PM
1️⃣ follows the general rule that "*concurrency must be explicit*"
e

Evan R.

02/06/2020, 10:31 PM
Also, the semantics of the two calls are different. In the first one, you suspend until doWork() is complete, then move on to the next line. In the second one, you launch a new coroutine into the provided scope and immediately continue without waiting for completion. This also means 1️⃣ is preferred because you can emulate 2️⃣’s behavior by doing the following in a coroutineScope:
Copy code
launch { CoroutineJob().doWork() }
b

bdawg.io

02/07/2020, 4:33 PM
And also gives you the flexibility to potentially retry on failure
Copy code
val myClass = CoroutineJob()
retry(maxAttempts=10) {
    myClass.doWork()
}
2 Views