Thomas S.
Thomas S.

Reputation: 6335

Scope functions vs. scopes in Coroutines

Kotlin comes with scope functions and coroutines also have scopes. Do both scopes are related or just named equally to confuse newbies?

Upvotes: 1

Views: 197

Answers (1)

PGliw
PGliw

Reputation: 451

TL;DR

Scope functions refer to scope in terms of variable scoping. Coroutine scopes refer to scopes in terms of structured concurrency. So scope functions have nothing to do with coroutine scopes and vice-versa.

Full answer:

Scope is a massivly overloaded term in computer science.

Scope functions refer to scope in terms of variable scoping That is:

val result = run {
   val x = 1
   val y = 2
   // x and y variables are visible here
   x + y
}
println(x) // compile-time error, variable x is not known here

Coroutine scopes refer to scopes in terms of structured concurrency. In that meaning, a scope defines how long the coroutine you started can live. You might start a coroutine in a global scope:

val globalJob = GlobalScope.launch {
   // do some fancy work here
}

It keeps executing until:

  • you finish the job manually (globalJob.join() or globalJob.cancel())
  • the work inside launch lambda is finished
  • the application process is finished - that is GlobalScope is finished

However, some components of your app may have shorter lifecycle than the whole application. Thus you may use eg. ViewModelScope which lives as long as Android ViewModel. All coroutines lauched in that scope are automatically cancelled when the lifecycle of the component (ViewModel) - and scope bound to it - ends.

Now you can see some similarities which explain why the same term - scope - is used in both cases:

Scope generally defines how long a thing lives.

So global variable is somehow similar to a coroutine launched in a GlobalScope.

However this similarity is only at the conceptual level - technically variable scoping is something completly different than coroutine scoping.

PS

The term Scope is also used in some DI frameworks (sometimes refered to as container), however this topic is out of scope of this answer :)

Upvotes: 6

Related Questions