Kotlin协程的简单用法(GlobalScope、lifecycleScope、viewModelScope)

Kotlin:lifecycleScope与GlobalScope以及MainScope的区别,详细分析为什么在Android中推荐使用lifecycleScope! 目录简要GlobalScopeMainScope()lifecycleScopelifecycleScope剩余问题分析(感兴趣的可以继续看) 简要 首先简要介绍一下kotlin协程作用域的三种类型。 类型 产生方式 异常传播特征 顶级作用域 GlobalScope创建 异常不向外传播。异常到达顶级作用域后,如果还没有被处理,会抛给当前的exceptionHandler,如果没有则给当前线程的uncaughtExceptionHandler 协同作用域 Job嵌套、coroutineSc 阅读详情

协程(Coroutine)

  • 协程就像非常轻量级的线程。线程是由系统调度的,线程切换或线程阻塞的开销都比较大。而协程依赖于线程,但是协程挂起时不需要阻塞线程,协程是由开发者控制的。所以协程也像用户态的线程,非常轻量级,一个线程中可以创建任意个协程。
  • 协程就像轻量级的线程。线程由系统调度,协程由开发者控制。
  • kotlin协程本质上是对线程池的封装。协程通过将线程切换的复杂性封装入库来简化异步编程。程序的逻辑可以在协程中顺序地表达,而底层库会为我们解决其异步性。

GlobalScope(不推荐)

  • GlobalScope.launch
    使用的是DefaultDispatcher,会自动切换到后台线程,不能做UI操作
 GlobalScope.launch {
        	//GlobalScope开启协程:DefaultDispatcher-worker-1
         	Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name)
			//子线程中此处不可以做UI操作
			//Toast.makeText(this@MainActivity, "GlobalScope开启协程", Toast.LENGTH_SHORT).show()
           
        }
  • 可以在协程中切换线程
GlobalScope.launch {
        	//GlobalScope开启协程:DefaultDispatcher-worker-1
         	Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name)
			//子线程中此处不可以做UI操作
			//Toast.makeText(this@MainActivity, "GlobalScope开启协程", Toast.LENGTH_SHORT).show()
			withContext(Dispatchers.Main){
                Toast.makeText(this@MainActivity, "协程中切换线程", Toast.LENGTH_SHORT).show()
            }
        }
  • GlobalScope.launch(Dispatchers.Main)
    通过Dispatchers.Main使协程依托于主线程中,此时可以更新UI等操作
 GlobalScope.launch(Dispatchers.Main) {
        	//GlobalScope开启协程:main
            Log.d(TAG, "GlobalScope开启协程:" + Thread.currentThread().name)
            //可以做UI操作
            Toast.makeText(this@MainActivity, "GlobalScope开启协程", Toast.LENGTH_SHORT).show()
        }

lifecycleScope、viewModelScope(推荐)

  • 引入方式
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'//lifecycleScope
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'//viewModelScope
  • GlobalScope是生命周期是process级别的,即使Activity或Fragment已经被销毁,协程仍然在执行。所以需要绑定生命周期。
  • lifecycleScope只能在Activity、Fragment中使用,会绑定Activity和Fragment的生命周期
  • viewModelScope只能在ViewModel中使用,绑定ViewModel的生命周期

协程的执行顺序

    private fun test() {
        Log.d(TAG, "test: 方法开始")
        lifecycleScope.launch {
            delay(1000)
            Log.d(TAG, "test: " + Thread.currentThread().name)
            Log.d(TAG, "test: 协程结束")
            Toast.makeText(this@MainActivity, "协程结束", Toast.LENGTH_SHORT).show()
        }
        Log.d(TAG, "test: 方法结束")
    }
D/MainActivity: test: 方法开始
D/MainActivity: test: 方法结束
D/MainActivity: test: main
D/MainActivity: test: 协程结束
  • 协程内的阻塞不会影响协程外
  • 由打印结果可以看出协程体是异步执行的,但是可以在其中做UI操作。线程也是异步的,但是不能更新UI,线程需要先切换到主线程。

协程中多个耗时任务的串行

  • 默认情况下协程中的内容是串行的
    private fun test2() {
        lifecycleScope.launch {
            val startTime = System.currentTimeMillis()
            val a = getDataA()
            val b = getDataB()
            val sum = a + b
            //D/MainActivity: test2: sum = 3,耗时:3008
            Log.d(TAG, "test2: sum = $sum,耗时:${System.currentTimeMillis() - startTime}")
        }
    }

    private suspend fun getDataA(): Int {
        delay(1000)
        return 1
    }

    private suspend fun getDataB(): Int {
        delay(2000)
        return 2
    }
D/MainActivity: test2: sum = 3,耗时:3008

协程中多个耗时任务的并行

  • 如果需要并行,例如请求多个接口拿到数据后才能进行操作
    private fun test3(){
        lifecycleScope.launch {
            val startTime = System.currentTimeMillis()
            val a = lifecycleScope.async { getDataA() }
            val b = lifecycleScope.async { getDataB() }
            val sum = a.await() + b.await()
            //D/MainActivity: test3: sum = 3,耗时:2009
            Log.d(TAG, "test3: sum = $sum,耗时:${System.currentTimeMillis() - startTime}")
        }
    }
    
    private suspend fun getDataA(): Int {
        delay(1000)
        return 1
    }

    private suspend fun getDataB(): Int {
        delay(2000)
        return 2
    }

D/MainActivity: test3: sum = 3,耗时:2009

协程的停止

  • 手动停止的情况 job?.cancel()
    private var job: Job? = null

    private fun test4() {
        job = lifecycleScope.launch {
            ...
        }
        job?.cancel()
    }
  • lifecycleScope和viewModelScope会绑定调用者的生命周期,因此通常情况下不需要手动去停止

suspend协程挂起原理

  • 在编译期,将suspend标记的方法转化成接口回调的方式,本质上还是基于回调实现的。
Kotlin协程使用 ​​) {​test1()​​return "网络数据..."​Log.i("cyc", "请求网络IO")Log.i("cyc", "逻辑处理")​​​flow {emit(0).flowOn(Dispatchers.IO)//作用于flow代码块.collect {​​​。 阅读详情

相关推荐

如何正确的在 Android 上使用 Kotlin 协程?

前言 你还记得是哪一年的 Google IO 正式宣布 Kotlin 成为 Android 一级开发语言吗?是 Google IO 2017 。如今两年时间过去了,站在一名 Android 开发者的角度来看,Kotlin 的生态环境越来越好了,相关的开源项目和学习资料也日渐丰富,身边愿意去使用或者试用 Kotlin 的朋友也变多了。常年混迹掘金的我也能明显感觉到 Kotlin 标签下的文章慢慢变...

ma1756295644的博客 1446

关于协程,你知道LifecycleScope吗,超详细解释给你听!

前言 使用协程,相信很多同学已经信手拈来了,但是也有很多同学是不知道LifecycleScope的。 LifecycleScope,顾名思义,具有生命周期的协程。 它是LifecycleOwner生命周期所有者的扩展属性,与LifecycleOwner生命周期绑定,并会在LifecycleOwner生命周期destroyed的时候取消掉。 推荐理由: 自动取消,不会造成内存泄漏,可以替代MainScope。 可以基于指定的生命周期执行。 后面会重点介绍LifecycleScope是怎么做到的。 使用

chuyouyinghe的专栏 1万+

RocketMQ 为什么要自己做一个 NameServer ?RocketMQ 5.x 版本中的 proxy、controller 和 container 分别有什么用 ?

1.独立运行的分散结构 2.简化实现,容忍部分数据不一致 Proxy:多语言支持、简化开发 Controller: 提高 Broker 的性能 Container:提高资源利用率,平衡负载

xaiobit_hl的博客 1493

Kotlin实战指南十五:协程泄漏

coroutines 引用 GlobalScope MainScope lifecycleScope lifecycleScope 是 KTX 下面的扩展包,Android 帮我们提供了一个扩展引用 使用 注意: 不需要我们手动 , 系统已经帮我们做好了是ViewModel的KTX扩展库,可以让我们在ViewModel中方便的使用Coroutine。如果想要在 ViewModel 中使用作用域,我们需要添加依稀: 使用: lifecycleScope 原理 个人微信号:zhaoyanjun125 ,

赵彦军 3570

LED背光驱动电路解析:从MP3394芯片到液晶屏灯管控制

本文深入解析了以MP3394芯片为核心的LED背光驱动电路工作原理。从升压电路的能量转换到多路LED的均流控制,详细阐述了其作为液晶屏背光“大脑”的关键作用,并提供了黑屏、闪屏、亮度不均等常见故障的实战检修思路与排查方法。

agile9scrum的博客 843

Yersinia:layer 2攻击框架!全参数详细教程!Kali Linux教程!

Yersinia是一个专为执行二层网络攻击设计的框架,利用多种网络协议的弱点进行渗透测试和网络分析。它支持针对生成树协议(STP)、思科发现协议(CDP)、动态中继协议(DTP)、动态主机配置协议(DHCP)、热备用路由器协议(HSRP)、802.1q、802.1x、交换机间链路协议(ISL)和VLAN中继协议(VTP)的攻击。这些攻击可能导致网络中的拒绝服务(DoS)或为更复杂的攻击创造条件。Yersinia对渗透测试人员和网络管理员非常有用,但使用时需谨慎,以免造成网络不稳定。

qq_24305079的博客 2290

Android折叠屏开发学习(一)---通过传感器获取铰链角度

学更好的别人,做更好的自己。——《微卡智享》本文长度为5289字,预计阅读8分钟前言Vivo在4月11号发布的X Fold折叠屏手机,也是抢了好几周好总算拿到手了,既然已经有了折叠屏手机,做为一个开发者,当然也要研究下折叠屏的开发,本篇就先简单介绍一下折叠屏的开发及通过传感器来获取到铰链的折叠角度,针对折叠屏的适配,Android官方推出了Jetpack WindowMa...

Vaccae的博客 2853

WPF毛玻璃效果别再写C#代码了!纯XAML用Border+VisualBrush+BlurEffect三步搞定

本文详细介绍了如何在WPF中通过纯XAML实现毛玻璃效果,无需编写C#代码。通过VisualBrush、BlurEffect和Clip的黄金组合,开发者可以快速创建专业级的毛玻璃面板,提升UI的现代感和视觉层次。文章还提供了性能优化技巧和实战案例,帮助开发者在各种场景中高效应用这一技术。

weixin_28630185的博客 357

194.lifecycleScope

lifecycleScope 是一个由 Android 提供的扩展属性,它为 LifecycleOwner(例如 Activity、Fragment)提供了一个预定义的 CoroutineScope(协程作用域)。通过这个作用域创建的协程会与 LifecycleOwner 的状态同步,当该组件销毁时,作用域内的所有协程会自动取消,避免内存泄露或一些由于组件生命周期导致的异常问题。

2303_79132118的博客 1393

Pytorch的一小步,昇腾芯片的一大步

相信在AI圈的人多多少少都看到了最近的信息:PyTorch最新2.1版本宣布支持华为昇腾芯片!

机器学习-深度学习-图像处理-opencv-段子 5259

【YOLO】YOLOV5-Seg的Segment模块解析

Segment模块同时输出检测结果和分割掩模,通过轻量级分割头实现实时实例分割

浩瀚之水的专栏 603

Kotlin协程的简单用法:1、GlobalScope(不建议使用);2、lifecycleScope、viewModelScope(建议使用);

Kotlin协程的简单用法:1、GlobalScope(不建议使用);2、lifecycleScope、viewModelScope(建议使用);

weixin_43936741的博客 1468

Unlocking Decoding-time Controllability: Gradient-FreeMulti-Objective Alignment with Contrastive Pr

将基于庞大网络语料库训练的大型语言模型(LLMs)(OpenAI,2023;Touvron 等,2023;Google,2023)与人类偏好对齐,是减少产生不安全(Wei 等,2023)、幻觉(Zhang 等,2023b)和有偏见(Gallegos 等,2023)内容的重要一步。随着偏好学习技术(如 PPO(Schulman 等,2017)、DPO(Rafailov 等,2023)及其他变体(Azar 等,2023;Ethayarajh 等,2024;

qq_52053775的博客 1170

kotlin各种Scope,MainScope/GlobalScope/viewModelScope/lifecycleScope/runBlocking/withContext

lifecycleScope是一个CoroutineScope的实例,它的生命周期与LifecycleOwner(通常是Activity或Fragment)的生命周期相同。lifecycleScope通常用于执行与Activity或Fragment相关的异步操作,例如启动Activity或Fragment时执行的异步任务。MainScope的生命周期通常是Activity或Fragment的生命周期,当它们被销毁时,MainScope也会被取消。

AdrianAndroid的专栏 3282

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Kotlin 协程 - 协程作用域 CoroutineScope

是一个接口。用来追踪内部启动的协程,并对它们进行有组织的统一管理(结构化并发),因此不能在协程作用域外启动协程。例如当Activity销毁后,协程还在执行,此时会造成资源浪费(内存、CPU、磁盘、无用网络请求)。协程作用域被cancel()取消的话,里面的子协程都会被取消。.......................................................................................

HugMua的博客 7997

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

正确的在 Android 上使用协程 ViewModelScope、LiveData、LifecycleScope

你还记得是哪一年的 Google IO 正式宣布Kotlin成为 Android 一级开发语言吗?是。如今两年时间过去了,站在一名 Android 开发者的角度来看,Kotlin 的生态环境越来越好了,相关的开源项目和学习资料也日渐丰富,身边愿意去使用或者试用 Kotlin 的朋友也变多了。常年混迹掘金的我也能明显感觉到 Kotlin 标签下的文章慢慢变多了(其实仍然少的可怜)。今年的 Google IO 也放出了的口号,许多新的 API 和功能特性将优先提供 Kotlin 支持。

chuyouyinghe的专栏 3521

Kotlin协程

一.协程的基本用法 kotlin没有把协程纳入标准库中,需要单独导入协程的依赖包: implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' 开启一个协程最简单的方式: GlobalScope.launch { println("The first coroutin

qq_37159335的博客 2527

Kotlin协程协程作用域,CoroutineScope MainScope GlobalScope viewModelScope lifecycleScope 分别代表什么

首先定义协程必须要制定其CoroutineScope他会跟踪所有协程。同样他还可以取消由它所启动的所有协程。GlobalScope声明周期是process级别的。即使Activty与Fragment已经被销毁,协程仍然在运行。MainScope 通常在 在Activity中使用。 在onDestory 要记得手动销毁掉。viewModelScope 只能在ViewModel中使用。绑定viewModel的生命周期lifecycleScope。只能在Activity、Fragment中使用。并且会和Activ

丿灬安之若死 1262

Kotlin协程中的作用域 `GlobalScope`、`lifecycleScope` 和 `viewModelScope`

与 Activity 或 Fragment 的生命周期绑定。当 Activity 或 Fragment 创建时,中启动的协程会随着 Activity 或 Fragment 的生命周期自动终止,避免内存泄漏。Kotlin协程提供了多种作用域来管理协程的生命周期,其中最常见的是。就创建了,当 Activity 或 Fragment 销毁时,是一个全局作用域,不受任何其他生命周期的限制。中启动的协程会一直运行,直到显式地取消或应用程序进程终止。的生命周期自动终止,避免内存泄漏。

micro9981的专栏 1292

Kotlin 协程避坑指南:GlobalScope vs Application Scope怎么选?

摘要: Kotlin协程中,GlobalScope因脱离生命周期管理易导致内存泄漏、UI异常等问题,而自定义的Application Scope绑定应用生命周期更安全可靠。GlobalScope的缺陷包括:与UI生命周期脱节、进程级存活造成资源浪费、缺乏结构化并发管理、测试困难等。正确做法是在自定义Application类中创建SupervisorJob作用域,通过onTerminate()统一取消协程,确保应用退出时资源释放。Application Scope既能全局调用,又可避免GlobalScope的

移动端开发干货分享 842

Android kotlin协程

GlobalScope.launch 不阻塞 继续执行主线程 后执行协程。coroutineScope.launch 不阻塞 继续执行主线程 后执行协程。runBlocking 阻塞主线程 执行了协程后 继续执行。runBlocking 阻塞主线程 执行了协程后 继续执行。结果 job继续执行 job1停了。结果 时间到后所在的协程也不继续执行了。结果: 执行的时候 job1加入了进来。结果 job 和 子job1都停了。1.1 协程里的挂起。

weixin_41648633的博客 937

Kotlin协程详解——协程作用域CoroutineScope

一、一、

闲暇部落 968
上一篇: Kotlin和Java互调空指针相关的问题(两种可能NullPointerException的情况)
下一篇: 推荐使用 Kotlin 关键字 Reified
hudawei996
博客等级 码龄17年 205粉丝 432原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值