currently i'm doing basically this: ``` private va...
# announcements
p
currently i'm doing basically this:
Copy code
private var job: Job

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

fun stop() {
    GlobalScope.launch { job.cancelAndJoin() }
}
`
p
Just call cancel, without a launch as you are not doing anything after you joined the job
1
g
+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
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
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
If join wasn't supsending it would be blocking the thread. That's what coroutines try to prevent