Hi there. When I want to create some immediately ...
# coroutines
b
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
I usually just pass coroutine scope in such case
Because it allows to stop it
b
@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
having to do scope.launch seems ugly to me
b
I see. Thanks!
g
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