https://kotlinlang.org logo
#android
Title
# android
v

Vinicius Carvalho

09/24/2018, 1:53 PM
Hi all, I'm still struggling to get coroutines and http to play nice with android, Is it correct to assume that
launch
should happen at the UI context if we need to update any component from the UI, and any networking call should happen on a
CommonPool
context?
g

gildor

09/24/2018, 2:34 PM
What is your library/API for http requests?
Yes, you need UI dispatcher to update views (UI is actually deprecated, use Dispatchers.Main instead) Question about CommonPool is more complicated, you http request shouldn't run on CommonPool (or Dispatchers.Default), request should be asyncronous: be non blocking or run on own thread pool, because you shouldn't run blocking operations on CommonPool, only dispatch non blocking ones
s

Sam

09/24/2018, 2:55 PM
@gildor Why do you suggest not using Dispatchers.Default for blocking io?
g

gildor

09/24/2018, 2:58 PM
This implementation of scoped view model is incorrect, instead implement CoroutineScope, check documentation of CoroutineScope
Because Dispatcher.Default is not intended to be blocked
If you block all the threads of this dispatcher no one can dispatch coroutines until some thread is available
Also this pool is very limited by default (only cpuNum - 1)
You should use IO dispatcher for blocking tasks
s

Sam

09/24/2018, 3:00 PM
Got it, in that case, isn't that true even for a long running non-blocking operation?
g

gildor

09/24/2018, 3:01 PM
Also
startTask
doesn't return job, so user of this APi cannot join or cancel this task
No, non-blocking operations is not a problem, but you also easily dispatch them from UI thread without explicit context switch to default dispatcher
s

Sam

09/24/2018, 3:02 PM
And in terms of implementing CoroutineScope, isn't that just a matter of choice? composing (than implementing) the scope in a member?
g

gildor

09/24/2018, 3:04 PM
Yes, you can use composition, but you don't expose scope of this view model, so cannot cancel it or run some task in the same scope from outside
s

Sam

09/24/2018, 3:06 PM
Ok got it, usually cleanup is triggered from another function within the ViewModel, onCleared and that has access to the scope
g

gildor

09/24/2018, 3:07 PM
Also your code incorrect, you do not create CoroutineScope instance, you just define new Coroutine context
s

Sam

09/24/2018, 3:11 PM
Oh its not mine, i just came across that in terms of default scope choice ( main vs background ). Anyways, I don't follow CoroutineScope instance. Isn't this a new instance?
Copy code
protected val scope: CoroutineScope = job + Dispatchers.Main