当前位置:网站首页>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
四、参考链接
边栏推荐
猜你喜欢

云原生应用平台的核心模块有哪些

365天挑战LeetCode1000题——Day 047 设计循环队列 循环队列

牛客刷题——剑指offer(第三期)

博云入选Gartner中国DevOps代表厂商

org.apache.ibatis.binding.BindingException Invalidbound statement (not found)的解决方案和造成原因分析(超详细)

Failed to configure mysql, what's going on?

翁恺C语言程序设计网课笔记合集

MSYS2 QtCreator Clangd 代码分析找不到 mm_malloc.h的问题补救

sqli-labs(less-11)

Hub and Spoke配置案例
随机推荐
Question about #oracle#, how to solve it?
The sitcom "Re-Walking the Long March" was staged
配置mysql失败了,这是怎么回事呢?
LayaBox---TypeScript---Three slash instructions
周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
LayaBox---TypeScript---声明合并
神通数据库,批量插入数据的时候失败
LayaBox---TypeScript---Namespaces and modules
从众多接口中脱颖而出的最稳定的接口——淘宝详情api
一体化在线政务服务平台,小程序容器技术加速建设步伐
AlphaFold又放大招,剑指整个生物界!
mysql清除binlog日志文件
全方位剖析Numpy中的np.diag源代码
Rear tube implements breadcrumb function
流动性质押挖矿系统开发如何制作?单双币系统开发成熟技术
多线程(基础) - 4万字总结
博云入选Gartner中国DevOps代表厂商
利用二维数据学习纹理三维网格生成(CVPR 2020)
LeetCode每日一练 —— 225. 用队列实现栈
sva 断言资料