Tuan Kiet
06/02/2019, 8:47 AMwithContext
to get this
as a coroutine context?tseisel
06/02/2019, 8:53 AMCoroutineScope
, not a CoroutineContext
.
The best way to obtain the CoroutineScope of a coroutine is to pass it as argument to the function that needs it.fun CoroutineScope.launchMyJob(...)
Functions defined like this does not suspend until the job is completed, as opposed to suspend fun
.simon.vergauwen
06/02/2019, 8:54 AMcoroutineContext
as a property available within any suspend
function or lambda.Tuan Kiet
06/02/2019, 9:00 AMsuspendCoroutineUninterceptedOrReturn
or withContext
simon.vergauwen
06/02/2019, 9:02 AMsuspendCoroutineOrReturn
is what you're looking for. It's rather low level.Tuan Kiet
06/02/2019, 9:25 AMgildor
06/02/2019, 9:49 AMTuan Kiet
06/02/2019, 9:56 AMcoroutineScope
pretty sure within a suspend function coroutineScope is a functionpublic suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R
gildor
06/02/2019, 9:57 AMTuan Kiet
06/02/2019, 9:57 AMcoroutineScope{}
or withContext{}
?gildor
06/02/2019, 9:59 AMTuan Kiet
06/02/2019, 10:01 AMgildor
06/02/2019, 10:02 AMTuan Kiet
06/02/2019, 10:05 AMsuspend fun sdfsdf(): Job {
return coroutineScope {
launch {
}
}
}
gildor
06/02/2019, 10:05 AMTuan Kiet
06/02/2019, 10:06 AMgildor
06/02/2019, 10:06 AMTuan Kiet
06/02/2019, 10:07 AMgildor
06/02/2019, 10:07 AMTuan Kiet
06/02/2019, 10:08 AMgildor
06/02/2019, 10:08 AMTuan Kiet
06/02/2019, 10:08 AMgildor
06/02/2019, 10:09 AMTuan Kiet
06/02/2019, 10:12 AMoverride suspend fun doWork(): Result = coroutineScope {
workJob = launch {
doActualWork()
}
workJob?.invokeOnCompletion {
if (it != null) {
showStoppedNotification()
}
}
Result.success()
}
private suspend fun doActualWork() {
// stuff
}
gildor
06/02/2019, 10:14 AMsuspend fun sdfsdf() {}
// On call site
val job = launch { sdfsdf() }
//Launch invocation in background and also may be cancelled
job.cancel()
Tuan Kiet
06/02/2019, 10:15 AMgildor
06/02/2019, 10:16 AMTuan Kiet
06/02/2019, 10:17 AMgildor
06/02/2019, 10:17 AMTuan Kiet
06/02/2019, 10:17 AMgildor
06/02/2019, 10:19 AMTuan Kiet
06/02/2019, 10:21 AMgildor
06/02/2019, 10:21 AMoverride suspend fun doWork(): Result {
try {
doActualWork()
} catch (e: CancellationException) {
// You can handle cancellation separately, if you want
} catch (e: Exception) {
showStoppedNotification()
//Should we return Result.fail()?
}
return Result.success()
}
private suspend fun doActualWork() {
// stuff
}
Tuan Kiet
06/02/2019, 10:23 AMdoWork
is called by that framework and canceled by the framework too, do we need doActualWork at all?gildor
06/02/2019, 10:24 AM//stuff
somewhere, isn’t it? I mean nothing prevents you from inline it in doWork, like with any other function, I’m not sure what is your concern in this caseTuan Kiet
06/02/2019, 10:25 AMgildor
06/02/2019, 10:29 AMTuan Kiet
06/02/2019, 10:35 AMgildor
06/02/2019, 10:38 AMDico
06/02/2019, 11:22 AMgildor
06/02/2019, 12:12 PM