lesincs
09/13/2021, 12:39 PMlesincs
09/13/2021, 12:41 PMGlobalScope
, seems it violates the rule of “structure concurrency”.
suspend fun someSuspendFunction() {
GlobalScope.launch {
// parallel task
}
// other logic
}
2. use coroutineScope
, seems good, but coroutineScope
will suspend until the inside coroutines finished, so it can’t meet my requirement.
suspend fun someSuspendFunction() {
coroutineScope {
launch {
// parallel task
}
}
// other logic
}
3. pass a CoroutineScope
from upstream, it works, but seems a little bit complex.
suspend fun someSuspendFunction(scope: CoroutineScope) {
scope.launch {
}
// other logic
}
Any good ways?streetsofboston
09/13/2021, 12:53 PMstreetsofboston
09/13/2021, 12:55 PMlesincs
09/13/2021, 1:06 PMif you want ‘other logic’ to be executed in parallel with code inside the ‘launch’, move ‘other logic’ inside coroutineScope’s lambda.Oh, thanks a lot! I try it and I think this is just what I want. 😀
Jacob
09/13/2021, 3:51 PMstreetsofboston
09/13/2021, 4:10 PMsuspend
and it suspends, or it takes a CoroutineScope
(either as its extension-parameter or as a regular parameter) and it returns immediately.
Option 3. would be ok only if it is clearly documented that the suspend function will suspend until its work is done but that a parallel task is being kicked off that may or may not finish before the suspend fun resumes.Jacob
09/13/2021, 4:52 PMJacob
09/13/2021, 4:53 PMScott Whitman
09/14/2021, 1:29 PMfun someRegularFunction1(scope: CoroutineScope) {
scope.launch {
// parallel task
}
scope.launch {
// other logic
}
}
fun someRegularFunction2(scope: CoroutineScope) = scope.launch {
launch {
// parallel task
}
launch {
// other logic
}
}
or as a suspend function returning the parallel task Job?
suspend fun someSuspendFunction(scope: CoroutineScope): Job {
val job = scope.launch {
// parallel task
}
// other logic
return job
}