return withContext() { // 从网络中读取用户数据 URL("https://example.com/user/$userId").readText() } } 1. 2. 3. 4. 5. 6. 在上面的代码中,fetchUserData是一个挂起函数,将从指定的URL中读取用户数据。withContext函数用于切换协程上下文,以便在IO线程上执行网络请
1) { println("launch before: ${Thread.currentThread().id}") withContext(dispatcher2) { println("withContext: ${Thread.currentThread().id}") println("zms") } println("launch after: ${Thread.currentThread().id}") } while (true); } launch before: 13 withContext: 14 zms launch after: ...
**使用一个线程我们id为11:运行完代码块1后,运行挂起函数withContext,withContext方法会有个返回值:如果是CoroutineSingletons.COROUTINE_SUSPENDED,则表示当前协程被挂起,挂起后,原执行代码块1的线程11被释放,这个时候线程11该干嘛干嘛去 待withContext内部代码块3 被执行完毕后,withContext内部会调用一个恢复函数resumeWith...
结论:runBlocking 是阻塞的 withContext使用样例 var job = GlobalScope.launch (Dispatchers.Main){ val result1 = withContext(Dispatchers.IO) { delay(2000) Log.d("test", "1协程执行—${Thread.currentThread().name}_id_${Thread.currentThread().id}") } val result2 = withContext(Dispatchers.IO) ...
val job = GlobalScope.launch(handler) { launch { try { delay(Long.MAX_VALUE) }finally { withContext(NonCancellable){ println("section 1") delay(100) println("section 2") } } } launch { delay(10) println("section 3") throw ArithmeticException() ...
2021-10-15 15:23:39.690 21612-21758/com.example.myapplication E/ytzn: 当前线程id = 3011 指定协程的线程类型 /*** 线程类型*/fun threadType() { GlobalScope.launch(Dispatchers.Default) {//默认线程Log.e(TAG, "Default当前线程id = " +Thread.currentThread().id) ...
//code 8val testFlow1=channelFlow{send(20)withContext(Dispatchers.IO){//可切换线程send(22)}}lifecycleScope.launch{testFlow1.collect{println("输出 = $it")}} 5、MutableStateFlow和MutableSharedFlow方法:都可以定义相应的构造函数去创建一个可以直接更新的热流。由于篇幅有限,有关热流的知识后面小节会再...
launch { // the first child try { delay(Long.MAX_VALUE) } finally { withContext(NonCancellable) { println("Children are cancelled, but exception is not handled until all children terminate") delay(100) println("The first child finished its non cancellable block") ...
CoroutineScope 会跟踪它使用 launch 或async 创建的所有协程。您可以随时调用 scope.cancel() 以取消正在进行的工作(即正在运行的协程)。在 Android 中,某些 KTX 库为某些生命周期类提供自己的 CoroutineScope。例如,ViewModel 有viewModelScope,Lifecycle 有lifecycleScope。不过,与调度程序不同,CoroutineScope 不运行...
We can launch coroutines in this scope without having to join them explicitly, because an outer coroutine(runBlocking in our example) does not complete until all the coroutines launched in its scope complete. 第一句话我们前面已经翻译过了,我们来看后面的: 我们可以不需要显式地join时,在这个作用域...