https://kotlinlang.org logo
Title
p

projectmoon

04/15/2019, 3:01 PM
currently i'm doing basically this:
private var job: Job

fun init() {
    GlobalScope.launch { job = launch { task() } }
}

fun stop() {
    GlobalScope.launch { job.cancelAndJoin() }
}
`
p

Paul Woitaschek

04/15/2019, 3:30 PM
Just call cancel, without a launch as you are not doing anything after you joined the job
1
g

gildor

04/15/2019, 4:22 PM
+1 to Paul, no reason to use join in your case, also use GlobalScope is not recommended for such case, better to have own scope, but it depends on case
p

projectmoon

04/15/2019, 7:53 PM
this is just a background thread that polls an API for information every few seconds. but it's good to know i can just cancel
i found it odd that join is a suspend function
what's the best way to define my own coroutine scope? the
coroutineScope
function requires me to be in a suspend function.
g

gildor

04/16/2019, 12:19 AM
This is not odd, join (same as cancelAndJoin) means "wait until this operation will be finished" and wait in coroutines is always means "suspend", which requires call from another suspend function/lambda not "block current thread" like in case of thread executor and join()
what's the best way to define my own coroutine scope?
Check docs of structured concurrency: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/basics.md#structured-concurrency Also this article by Roman is useful and explains general idea of this approach https://medium.com/@elizarov/structured-concurrency-722d765aa952
Also check docs of CoroutineScope interface it has an example of class that implements CoroutineScope and manage lifecycle of this scope https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html
p

Paul Woitaschek

04/16/2019, 8:29 AM
If join wasn't supsending it would be blocking the thread. That's what coroutines try to prevent