当前位置:网站首页>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、基础用法
凡是实现了LifecycleOwnerInterface 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,比如说onStartWhen start coroutines,onStopTime 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
repeatOnLifecycleActivities 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
四、参考链接
边栏推荐
- How to choose a truly "easy-to-use, high-performance" remote control software
- 21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
- Outsourced Student Management System Architecture Documentation
- 保姆级教程:写出自己的移动应用和小程序(篇二)
- 2022年8月初济南某外包公司全栈开发面试题整理
- 21 Days Learning Challenge - Day 1 Punch (Screen Density)
- LayaBox---TypeScript---命名空间和模块
- 划分训练集,验证集,测试集
- 如何在技术上来保证LED显示屏质量?
- ECCV22|PromptDet:无需手动标注,迈向开放词汇的目标检测
猜你喜欢
随机推荐
ASP.NET Core 6框架揭秘实例演示[31]:路由&quot;高阶&quot;用法
如何封装微信小程序的 wx.request() 请求
Event 对象,你很了解吗?
Jay Chou's new song is released, crawl the "Mojito" MV barrage, and see what the fans have to say!
初探zend引擎
SQL 经典50题(题目+解答)(1)
Multithreading (Basic) - 40,000 word summary
games202:三,实时环境光照IBL + PRT
Turning and anti-climbing attack and defense
21 Days Learning Challenge - Day 1 Punch (Screen Density)
Hello, my new name is "Bronze Lock/Tongsuo"
LayaBox---TypeScript---三斜线指令
Mysql事务隔离级别与MVCC(多版本并发控制)
LayaBox---TypeScript---命名空间和模块
暑期总结3
The 38-year-old daughter is not in love and has no stable job, the old mother is crying
21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
AdguardHome如何配置设置?我的AdguardHome配置内容过滤器拦截列表
MSYS2 QtCreator Clangd code analysis can not find mm_malloc.h problem remedy
MySQL模糊查询性能优化









