https://kotlinlang.org logo
Title
t

Tuan Kiet

07/24/2019, 8:32 AM
is
GlobalScope
considered bad practice, what is the specific use case of it?
g

gildor

07/24/2019, 8:33 AM
When you really need global background state
Also for some adapters, like for RxJava, where you just want to delegate lifecycle management to subscriber
😒uspend: 2
u

uhe

07/24/2019, 8:34 AM
I really, really don't think that using
GlobalScope
can always be considered bad practice.
g

gildor

07/24/2019, 8:35 AM
In most of cases it is
u

uhe

07/24/2019, 8:37 AM
Is there a list of "most of cases" that I can check?
g

gildor

07/24/2019, 8:38 AM
just checking with our code base
u

uhe

07/24/2019, 8:38 AM
I'm asking this because most of the official examples that I have seen that advocate structured concurrency are tied to very specific use cases.
g

gildor

07/24/2019, 8:38 AM
I disagree
why they are specific?
we now even injecting scope for top level global tasks, which before were just global, now has user session lifecycle
u

uhe

07/24/2019, 8:39 AM
Specific in a way that prevents me from applying them in my contexts
Maybe that's just me, though. Sorry for derailing the discussion.
g

gildor

07/24/2019, 8:42 AM
What is your context? Do you have an example?
a

Antanas A.

07/24/2019, 8:42 AM
It's considered bad practices because you cannot control that run in your test suites
Haven't worked for us, and every time we've converted
GlobalScope.launch
call into explicitlyPassedScope.launch { }
for example you cannot simulate time line in tests so code with some
delay(...)
calls cannot be tested fast
Also, you can still change the dispatcher / job that you pass to
GlobalScope.launch
in your tests
g

gildor

07/24/2019, 8:48 AM
It’s considered bad practices because you cannot control that run in your test suites
I think it’s wrong assumption. It’s bad practice because it’s global background job whicch should be explicitly handled and in most cases it may be avoided And yeah test such side effects is also probably bad practice by itself, better to test suspend functions
for example you cannot simulate time line in tests so code with some
delay(...)
calls cannot be tested fast
You still can inject custom context to launch, it has nothing to do with GlobalScope, it’s the same as with any other scope
👍 1
s

streetsofboston

07/24/2019, 11:45 AM
For testability, we inject the scope on which an instance ('s launches) run, at runtime. That allows us to inject a testCoroutineScope when running unit-tests. Even during injection, we don't often inject GlobalScope, and inject CoroutineScope(someJob + someDispatcher) instead.