https://kotlinlang.org logo
c

Cicero

10/31/2021, 4:13 PM
Hey, I saw a lot of "Reasons not to use GlobalScope" but what are the alternatives when you can't reach a scope? Do I always need to pass down an activity reference? I have a singleton watching network state and pushing this state as it changes into a singleton flow. The way I need to handle some of this processing will always require a thread but it's not guaranteed I will have short access to a scope. What is your solution? What is our community default solution?
b

Big Chungus

10/31/2021, 4:16 PM
You can create your own coroutine scope with CoroutineScope() factory function and close it when no longer needed
c

Cicero

10/31/2021, 4:18 PM
Copy code
fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    // ...
): Job
From https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055 ?
Ok, but then how do I close? Does the run blocking already resolves the issue automagically?
b

Big Chungus

10/31/2021, 4:21 PM
Scope normally closes itself when all jobs complete, but you can also close it manually
c

Cicero

10/31/2021, 4:22 PM
Ok, thanks man, I will hit that hint you gave me
Hopefully this will save from all my references to GlobalScope
❤️
b

Big Chungus

10/31/2021, 4:49 PM
Good luck!
c

Cicero

10/31/2021, 5:18 PM
Didn't really solve my problem, I'm still trying to get around the issue
I need to emit a flow from a place I wouldn't have conventional access to a context. Should I just create a global reference to my activities context?
b

Big Chungus

10/31/2021, 5:31 PM
Well global custom CoroutineScope is still better than GlobalScope, because you can close it whenever you want without having to worry about it being used by some of the libs
☝🏻 1
c

Cicero

10/31/2021, 5:34 PM
But how do I create a scope when there is no scope?
The only reason I'm using Global is to avoid hoisting trough 5 layers just to ask for a scope
Copy code
fun dismissFeedback() {
    runBlockingTest{
        NetworkFeedback.feedback.emit(Finish)
    }
}

fun runBlockingTest(test: suspend CoroutineScope.() -> Unit) =
    CoroutineScope(EmptyCoroutineContext).produce<Unit>(block = test)

fun networkRequestTrigger() {
    runBlockingTest{
        NetworkFeedback.feedback.emit(Request)
    }
}
❤️
A question o elbow grease
But now I'm curious if this is the best approach 🙂
b

Big Chungus

10/31/2021, 6:30 PM
Not sure if it's the best, but definitely better than GlobalScope
💪🏽 1
Might be good to reuse your custom scope between tests, tho
c

Cicero

10/31/2021, 6:34 PM
Awesome, this is satisfactory