Hi. I'm relatively new to Coroutines. Is it okey t...
# coroutines
j
Hi. I'm relatively new to Coroutines. Is it okey to use
GlobalScope.launch { }
to run an infinite while to draw on canvas (Android SurfaceView) or it is a better solution ?
z
no
Views have a lifecycle
UI has a lifecycle (activities, fragments, etc)
and that lifecycle is not global
j
Ok, so I must run the coroutine attached to the lifecycle of the view.
z
so if you use global scope, your coroutine will continue to run when the view or activity is destroyed
j
Ok, and stop running only when the app is destroyed, is that ?
👍 1
z
for example, if it were activity:
Copy code
lateinit var onCreateScope: CoroutineScope
fun onCreate(){
  onCreateScope = CoroutineScope(Dispatchers.Main)  
}

fun onDestroy() {
  onCreateScope.cancel()
}
j
So I don't need a
job
propertie and I can directly call
surfaceViewScope.cancel()
in
surfaceDestroyed()
, if I'm right 🙂
z
correct
that’s what is awesome about scopes 🙂
you define lifecycle (the scoping) first, then you can launch coroutines!
j
It's still a bit unatural to have to define it explicitly, but I understand the concept, thanks for the help !
👍 1
Lot of time, if you use LifeCycle librabry, I think you can attached coroutine to the lifecycleowner
☝️ 1
Because my needed was to have a background worker for the
SurfaceView
, I was been able to define directly my propertie on declaration with
private val surfaceViewScope = CoroutineScope(Dispatchers.Default)
, I guess it's right 😬
👍 1
z
just make sure you switch to the main thread for main specific code
👍 1
j
Like it, must spend more time on Coroutines
z
also, realize that
Dispatchers.Default
is a thread pool, so if you launch more than one coroutine you lose thread safety (any code confined to a single coroutine is thread safe, even if it runs across multiple threads)
j
Ok thanks, in my case it's Ok I guess.
It's the same for the
IO
dispatcher ?
z
yes, but the
IO
dispatcher is for blocking calls that don’t do any work while they block a thread
👍 1