https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

gildor

10/15/2018, 1:51 PM
I don't see any safely issues with the first. But you cannot use first approach in some cases. For example you cannot use it for Android Fragments when Job can be recreated
l

louiscad

10/15/2018, 2:04 PM
I checked for Fragment.viewLifecycleOwner, an a new one is generated on each view creation (including retained fragments), so now I'm confident the first approach is correct (and the second is the same but with extra allocation)
g

gildor

10/15/2018, 3:20 PM
Sure, if you connect it to viewLifecycleOwner
It still can make sense for similar code with complicated lifecycle. But I think one should use one everywhere when it's possible
Also instead updating Job each time you can update coroutineContext instead to avoid allocation on access
l

louiscad

10/15/2018, 4:56 PM
That's right, although I'm not sure it's worth the hassle managing such reuse, especially when all the view has been destroyed and will be created again (which is orders or magnitude more allocation)
k

kingsley

10/16/2018, 7:36 AM
I do use the first one like:
Copy code
override val coroutineContext = SupervisorJob() + Dispatchers.Main
No extra field is needed, since I can easily do
coroutineContext.cancel()
directly. I use the supervisor job since I only want it to be explicitly canceled
2 Views