wanandroid icon indicating copy to clipboard operation
wanandroid copied to clipboard

viewModelScope.launch 默认在主线程执行,block耗时操作有问题吧

Open sunqi94600 opened this issue 4 years ago • 6 comments

/** * 创建并执行协程 * @param block 协程中执行 * @param error 错误时执行 * @return Job */ protected fun launch(block: Block<Unit>, error: Error? = null, cancel: Cancel? = null): Job { return viewModelScope.launch { try { block.invoke() } catch (e: Exception) { when (e) { is CancellationException -> { cancel?.invoke(e) } else -> { onError(e) error?.invoke(e) } } } } }

sunqi94600 avatar May 20 '20 14:05 sunqi94600

block执行的方法都是suspend 修饰的,耗时操作会挂起,应该没有问题吧

zenghuiwang avatar Jun 29 '20 03:06 zenghuiwang

为什么没用withContext(Dispatchers.IO)?

andev009 avatar Jul 20 '20 10:07 andev009

这点我也有点不明白,不过retrofit的网络请求都是有自己的线程池的,不明白它们请求结果是怎么又切换回主线程的

yu893145181 avatar Sep 10 '20 01:09 yu893145181

这是个 viewModelScope , 看看 viewModelScope 代码大概能懂

Crazy-MT avatar Sep 22 '20 05:09 Crazy-MT

Retrofit自己切了线程

jiayuanfa avatar Dec 03 '20 06:12 jiayuanfa

这是retrofit默认开启了异步请求???

xingxing16 avatar Apr 25 '21 11:04 xingxing16