一个这样的库函数是withContext,它是你需要解决你的问题的那个。它用你传递给它的块创建另一个协程,...
Coroutines always execute in some context that is a set of various elements. Below are main elements of coroutine context Job – models a cancellable workflow with multiple states and a life-cycle that culminates in its completion. Launch returns a Job object. When you launch a coroutine, you...
launch(start = CoroutineStart.DEFAULT, context = Dispatchers.Default) { log(1) delay(500) log(2) } // output Thread[DefaultDispatcher-worker-1,5,main]1 Thread[DefaultDispatcher-worker-1,5,main]2 Thread[main,5,main]end 1. 2. 3. 4. 5. 6. 7. 8. 9. 小结: 其实kotlin的默认的几...
classJetpackCoroutineViewModel:ViewModel() {//在这个ViewModel中使用协程时,需要使用这个job来方便控制取消privatevalviewModelJob = SupervisorJob()//指定协程在哪里执行,并且可以由viewModelJob很方便地取消uiScopeprivatevaluiScope = CoroutineScope(Dispatchers.Main + viewModelJob)funlaunchDataByOldWay(){ uiScope...
通过前面的文章,我们知道coroutine其实就是一个任务,对于这个任务的执行,协程线程框架,给我们提供了 二样东西,分别是上下文、启动模式。 我们使用二种东西可以控制任务在线程框架的运行。 一、启动协程,以及一些协程常用类介绍: publicfunCoroutineScope.launch(context:CoroutineContext=EmptyCoroutineContext,start:Coroutine...
launch { //在后台执行 val result = getNetData() //修改UI log(result) } } //将耗时任务切到IO线程去执行 private suspend fun getNetData() = withContext(Dispatchers.IO) { //模拟网络耗时 delay(1000) //模拟返回结果 "{}" } } 所有CoroutineScope的初始化和取消都已经为我们完成了,只需要在...
lifecycleScope.launch(Dispatchers.IO) { try { val bitmap = contentResolver.loadThumbnail( uri, Size(224, 224), null ) val results = classifier.classify(bitmap) withContext(Dispatchers.Main) { ivPreview.setImageBitmap(bitmap) showResults(results) ...
class TestClass{ private var string = "Hello" fun testError() { string= "It Works" GlobalScope.launch(Dispatchers.Default) { withContext(Dispatchers.Main) { string = "Doesn't work" } } } } 但它仍然抛出一个错误: kotlin.native.concurrent.InvalidMutabilityException:冷冻com.example.project.Test...
If several coroutines are waiting to be executed next, the one scheduled after the smallest delay will be chosen. The virtual time will automatically advance to the point of its resumption. @TestfuntestWithMultipleDelays()=runTest { launch { delay(1_000)println("1.$currentTime")//1000delay...
ThewithContext()invocation withDispatchers.Default,Dispatchers.IO, or their views attempts not to switch threads when possible. A view doesn’t need to be closed. To create separate executors, you can take multiple views of the same dispatcher and they will share threads and resources. There is...