当前位置:网站首页>Coroutines and Lifecycle in Kotlin
Coroutines and Lifecycle in Kotlin
2022-08-02 11:00:00 【Mr_Tony】
文章目录
一、前言
kotlinCoroutines in sometimes very convenient.jetpackProvides enough compatible,Here to record some of its
二、引入依赖
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.fragment:fragment-ktx:1.5.0'
implementation 'androidx.activity:activity-ktx:1.5.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1'
三、代码示例
1、基础用法
凡是实现了LifecycleOwner
Interface class can use the following way open coroutines,例如Fragment
、ComponentActivity
及其子类
//You can use the following way open association degree,Advantage is not to deal with page after the closing
lifecycleScope.launch {
}
ViewModel
viewModelScope.launch {
}
2、repeatOnLifecycle
If there is a demand according to the page life cycle must be,比如说onStart
When start coroutines,onStop
Time to stop coroutines,可以使用以下方式.The life cycle is calledCan restart the life cycle of perceptual coroutines
override fun onCreate(savedInstanceState: Bundle?) {
lifecycleListener()
}
private fun lifecycleListener(){
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED){
while (isActive){
delay(1000)
Log.e("YM---->","线程运行中....")
}
}
}
}
3、flowWithLifecycle
If it is only on a data streamFlow
进行监听,可以使用以下方式
private fun lifecycleListener(){
lifecycleScope.launch {
(1..9).asFlow().flowWithLifecycle(lifecycle,Lifecycle.State.STARTED).collect{
println("YM---->value:$it")
}
}
}
由于flowWithLifecycle
是Flow
的函数,So it can be hung on in heatStateFlow
或ShareFlow
上面.Multiple streams can also use the aboverepeatOnLifecycle
的方式
4、lifecycle.whenCreated、lifecycle.whenStarted 和 lifecycle.whenResumed
repeatOnLifecycle
Activities can be limited within a certain range,But this will come as the life cycle of repeated repeated start,但是假如,Only use a word you don't need so much,可以使用以下方式,
class MyFragment: Fragment {
init {
lifecycleScope.launch {
whenStarted {
}
}
//或者
lifecycleScope.launchWhenCreated {
}
}
}
5、协程与LiveData
在使用LiveData
时候,We sometimes need to asynchronous access to content,Usually is to createLiveData
,然后在onCreate()
To take the initiative to load the data,This way can simplify the operation
private val user: LiveData<Int> = liveData {
// val data = database.loadUser() // loadUser is a suspend function.
//delay(5000)
emit(10)
}
override fun onCreate(savedInstanceState: Bundle?) {
lifecycleListener()
}
private fun lifecycleListener(){
user.observe(this){
Log.e("YM---->"," 参数:$it")
}
}
以下引用自官网
当 LiveData 变为活动状态时,代码块开始执行;当 LiveData
变为非活动状态时,代码块会在可配置的超时过后自动取消.如果代码块在完成前取消,则会在 LiveData
再次变为活动状态后重启;如果在上次运行中成功完成,则不会重启.请注意,代码块只有在自动取消的情况下才会重启.如果代码块由于任何其他原因(例如,抛出
CancellationException)而取消,则不会重启.
当页面进入onStop
时候,Will not send until the restore data page,才会发送数据,需要注意的是,实际测试中,Logic does not perform again,But in the next time the already loading the data sent directly
四、参考链接
边栏推荐
- 有奖征集|TaoCloud&宝德联合举办全闪POC!
- LayaBox---TypeScript---Namespaces and modules
- LayaBox---TypeScript---Iterator and generator
- LeetCode每日一练 —— 225. 用队列实现栈
- The sitcom "Re-Walking the Long March" was staged
- ansible模块--copy模块
- 【术语科普】关于集成工作台那些难懂的词儿,看这篇秒懂!
- MSYS2 QtCreator Clangd code analysis can not find mm_malloc.h problem remedy
- 翁恺C语言程序设计网课笔记合集
- 周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
猜你喜欢
云原生应用平台的核心模块有哪些
同样做软件测试,和月收入 3W 的学弟聊了一晚上,我彻底崩溃了
MapStruct
How to technically ensure the quality of LED display?
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
After 21 years of graduation, I switched to software testing. From 0 income to a monthly salary of over 10,000, I am really lucky...
Com多进程通信实现
365天挑战LeetCode1000题——Day 047 设计循环队列 循环队列
21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
详细总结SoC、DSP、MCU、GPU和FPGA等基础概念
随机推荐
云原生应用平台的核心模块有哪些
从零开始Blazor Server(5)--权限验证
5G基础学习1、5G网络架构、网络接口及协议栈
LeetCode每日一练 —— 225. 用队列实现栈
games202:三,实时环境光照IBL + PRT
leetcode: 200. 岛屿数量
注意力机制
WPF 截图控件之文字(七)「仿微信」
8年软件测试工程师的感悟:与薪资相匹配的永远是实力
LayaBox---TypeScript---JSX
Rear tube implements breadcrumb function
Mysql环境变量的配置(详细图解)
C#/VB.NET 添加多行多列图片水印到Word文档
sva 断言资料
“纯C”实现——三子棋小游戏
STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)
小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~
LayaBox---TypeScript---模块
How to choose a truly "easy-to-use, high-performance" remote control software
C#/VB.NET to add more lines more columns image watermark into the Word document