Hi all, I'm still struggling to get coroutines and...
# android
v
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
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
@gildor Why do you suggest not using Dispatchers.Default for blocking io?
g
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
Got it, in that case, isn't that true even for a long running non-blocking operation?
g
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
And in terms of implementing CoroutineScope, isn't that just a matter of choice? composing (than implementing) the scope in a member?
g
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
Ok got it, usually cleanup is triggered from another function within the ViewModel, onCleared and that has access to the scope
g
Also your code incorrect, you do not create CoroutineScope instance, you just define new Coroutine context
s
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