https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bnn

10/02/2019, 10:19 PM
Hi there. When I want to create some immediately returning method in a class, I usually write class in following manner.
Copy code
class Foo(ctx: CoroutineContext) {
    val scope = CoroutineScope(ctx)

    fun launchSome() = scope.launch { ... }
}
Are there better ways or conventions to do that? I wonder some possibilities such as ... - To implement CoroutineScope (
class Foo(ctx: CoroutineContext = ... : CoroutineScope { ... }
) - To define method as CoroutineScope extension function (
fun CoroutineScope.launchSome() = launch(ctx) {...}
) Thanks.
g

gildor

10/03/2019, 10:22 AM
I usually just pass coroutine scope in such case
Because it allows to stop it
b

bnn

10/03/2019, 2:34 PM
@gildor Thanks for feedback. So, you meant like this.
Copy code
class Foo(private val scope: CoroutineScope) {
  fun launchSome() = scope.launch { ... }
}
Is my understanding correct?
l

Luis Munoz

10/03/2019, 3:12 PM
having to do scope.launch seems ugly to me
b

bnn

10/04/2019, 3:01 AM
I see. Thanks!
g

gildor

10/04/2019, 3:30 AM
I don't like implement scope, essentially you leak your scope to outside. Sometimes it's fine, but in most cases it's unnecessary and you leak scope outside (which also can be cancelled)
Also, I see that
launchSome
is public, are you sure that you need scope in Foo? Maybe just pass it to launchSome, or, even better, just make it suspend and let user of this function decide about target scope
@Luis Munoz "someDispatcher" looks incorrect, because you also should cache Job somewhere and pass it to CoroutineScope, not only dispatcher, otherwise every new coroutine will have own job and it breaking structured concurrency
2 Views