https://kotlinlang.org logo
Title
d

deviant

03/08/2019, 3:02 PM
is it possible to get coroutine scope object inside of coroutine? for example:
private suspend fun <E> ReceiveChannel<E>.throttle(): ReceiveChannel<E> {
    // want to launch {} in current scope
}
w

withoutclass

03/08/2019, 3:20 PM
I think you would provide scope as a parameter to
throttle
, then use that scope to
launch
d

deviant

03/08/2019, 3:42 PM
hmm. not very convenient. no other ways?
s

sitepodmatt

03/08/2019, 3:49 PM
coroutineScope(coroutineContext) { } ?
although I recall they dont recommend this way
d

deviant

03/08/2019, 3:51 PM
the signature doesn't allow this
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R
and i would like to run the
launch
in worker thread
i mean return result immediately
s

sitepodmatt

03/08/2019, 3:52 PM
one sec
d

deviant

03/08/2019, 3:54 PM
do you mean?
val scope = CoroutineScope(Dispatchers.Default)
scope.launch(Dispatchers.Default) {...}
s

sitepodmatt

03/08/2019, 3:54 PM
CoroutineScope(coroutineContext).run {
                    launch {
                        
                    }
                    
                }`
d

deviant

03/08/2019, 3:55 PM
looks legit. thanks
I recall they dont recommend this way
do you know why?
s

sitepodmatt

03/08/2019, 3:56 PM
I guess because you're technically creating a new CoroutineScope it just has all the elements of the one of the caller. There's another way too. Not sure though
ah nevermind you're already using ReceiveCHannel as the receiver
g

gildor

03/09/2019, 12:01 AM
not very convenient
This is the most explicit and safe way, because caller knows exactly on which scope new coroutine will be executed, now instead you create new scope that uses job of parent But I would say that for this particular use case it's probably fine to make this channel`s operator signature clear