Melih Aksoy
07/22/2021, 9:29 AMprivate var job: Job? = null
set(value) {
println("Setting value")
field = value
}
job = lifecycleScope.launch() {
println("Started")
try {
println("Try")
} catch (e: CancellationException) {
println("Catch")
} finally {
println("Finally")
}
}
prints
Started
Try
Catch
Finally
Setting value
in order.
Which means when using default coroutine start, launch
returns job
reference after contents are executed ( if execution is fast enough ). So thereās no guarantee when youāll be handled job
reference when you do the assignment. I didnāt find any mention of this in any docs, but I was expecting it to at least wait for reference to be handled before starting execution š¤
This is probably troublesome in scenarios if you do an if ( job != null ) return
check or similar ( clear in finally
( finally { job = null }
). You may end up job
being assigned and not getting cleared.
P.S. Using CorotuineStart.LAZY
followed by job?.start()
resolves this issue, Iām just asking if is this expected from default implementation š¤ ?wasyl
07/22/2021, 9:31 AMimmediate
scheduler, which executes the contents in-place if the coroutine is already started on the UI thread (unless a suspension point is hit)ephemient
07/22/2021, 9:32 AMephemient
07/22/2021, 9:32 AMMelih Aksoy
07/22/2021, 9:32 AMephemient
07/22/2021, 9:34 AMephemient
07/22/2021, 9:36 AMMelih Aksoy
07/22/2021, 9:36 AMMelih Aksoy
07/22/2021, 9:38 AMfun something() {
if ( job != null ) return
job = launch { ... }
}
Melih Aksoy
07/22/2021, 9:38 AMMelih Aksoy
07/22/2021, 9:41 AMephemient
07/22/2021, 9:58 AMvar
-ectomy?
val parentJob = Job(lifecycleScope.coroutineContext.job)
parentJob.cancelChildren() // cancel previous jobs without races
lifecycleScope.launch(parentJob) {
// do work
}