peekandpoke
05/27/2021, 6:46 AMkotlinx-coroutines 1.5.0
and this now has marked the GlobalScope as a delicate API.
I totally understand the reason behind this but I am somewhat stuck now. So my question is:
How can I create a CoroutineScope
that I will then be reusing? I am doing this now:
val scope = CoroutineScope(EmptyCoroutineContext)
... and then I reuse this scope. Does this make any sense?
And similar in KotlinJS when using Flows we often times have code like this:
fun callApi() {
GlobalScope.launch {
api.getStuff().collect { // collect() is a suspend function so it needs a coroutine scope
...
}
}
}
What would be a clean way to get a reusable coroutine scope here?
Thanks in advance!CLOVIS
05/27/2021, 8:02 AMGlobalScope
to launch your API calls: that isn't structured concurrency.
If your API has some kind of authentication or whatever, one good solution would be to create a Job in the class that handles authentication, and use that one to launch
. This way, you have a single object that can cancel all ongoing requests, if you need to.Robert Jaros
05/27/2021, 8:20 AMpeekandpoke
05/27/2021, 9:50 AMval scope = CoroutineScope(EmptyCoroutineContext)
How will this scope behave?CLOVIS
05/27/2021, 9:52 AMClient
has a scope, Authenticator
as well, but pretty much everything doesn't (it just calls suspending function from the client, which use the client's scope). Each ‘scoped' class takes an optional parent job as a parameter, so the main function can declare a job that the whole application then depends on, so the main function can then cancel everything else when it's done with what it has to dopeekandpoke
05/27/2021, 9:56 AMCLOVIS
05/27/2021, 10:07 AMprivate val scope = CoroutineScope(job + <whatever dispatcher makes sense here>)
peekandpoke
05/27/2021, 10:32 AMsteamstreet
06/03/2021, 9:02 PMMainScope
which I’m not at all sure what that is. https://play.kotlinlang.org/hands-on/Building%20Web%20Applications%20with%20React%20and%20Kotlin%20JS/08_Using_an_External_REST_APICLOVIS
06/03/2021, 9:10 PMclass Client(..., parent: Job? = null) {
private val scope = CoroutineScope(SupervisorJob(parent) + <http://Dispatchers.IO|Dispatchers.IO>)
// The rest of your class, with a 'send' method or whatever
// When you need to launch you use the scope
fun close() {
scope.cancel() // kills all ongoing requests
// Your GraphQL closing logic
....
}
}
// In some other file
fun Client.myRequest1(...) {
...
// Uses Client.send, so it uses the client's scope
}
I'm not sure this pattern is recommended by the Kotlin team, but I've used it and it feels quite nice.