https://kotlinlang.org logo
Title
j

Jérôme Gully

11/07/2019, 10:45 PM
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

zak.taccardi

11/07/2019, 10:46 PM
no
Views have a lifecycle
UI has a lifecycle (activities, fragments, etc)
and that lifecycle is not global
j

Jérôme Gully

11/07/2019, 10:47 PM
Ok, so I must run the coroutine attached to the lifecycle of the view.
z

zak.taccardi

11/07/2019, 10:47 PM
so if you use global scope, your coroutine will continue to run when the view or activity is destroyed
j

Jérôme Gully

11/07/2019, 10:47 PM
Ok, and stop running only when the app is destroyed, is that ?
👍 1
z

zak.taccardi

11/07/2019, 10:48 PM
for example, if it were activity:
lateinit var onCreateScope: CoroutineScope
fun onCreate(){
  onCreateScope = CoroutineScope(Dispatchers.Main)  
}

fun onDestroy() {
  onCreateScope.cancel()
}
j

Jérôme Gully

11/07/2019, 10:48 PM
So I don't need a
job
propertie and I can directly call
surfaceViewScope.cancel()
in
surfaceDestroyed()
, if I'm right 🙂
z

zak.taccardi

11/07/2019, 10:52 PM
correct
that’s what is awesome about scopes 🙂
you define lifecycle (the scoping) first, then you can launch coroutines!
j

Jérôme Gully

11/07/2019, 10:56 PM
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

zak.taccardi

11/07/2019, 10:59 PM
just make sure you switch to the main thread for main specific code
👍 1
j

Jérôme Gully

11/07/2019, 10:59 PM
Like it, must spend more time on Coroutines
z

zak.taccardi

11/07/2019, 11:00 PM
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

Jérôme Gully

11/07/2019, 11:04 PM
Ok thanks, in my case it's Ok I guess.
It's the same for the
IO
dispatcher ?
z

zak.taccardi

11/07/2019, 11:16 PM
yes, but the
IO
dispatcher is for blocking calls that don’t do any work while they block a thread
👍 1