is `GlobalScope` considered bad practice, what is ...
# coroutines
t
is
GlobalScope
considered bad practice, what is the specific use case of it?
g
When you really need global background state
Also for some adapters, like for RxJava, where you just want to delegate lifecycle management to subscriber
⏸️ 2
u
I really, really don't think that using
GlobalScope
can always be considered bad practice.
g
In most of cases it is
u
Is there a list of "most of cases" that I can check?
g
just checking with our code base
u
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
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
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
What is your context? Do you have an example?
a
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
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
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.