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

Turning and anti-climbing attack and defense

小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~

Hello, my new name is "Bronze Lock/Tongsuo"

Three.JS程序化建模入门

同样做软件测试,和月收入 3W 的学弟聊了一晚上,我彻底崩溃了

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

You Only Hypothesize Once: 用旋转等变描述子估计变换做点云配准(已开源)

Com多进程通信实现

超赞!发现一个APP逆向神器!

MSYS2 QtCreator Clangd 代码分析找不到 mm_malloc.h的问题补救
随机推荐
零代码工具推荐---HiFlow
全方位剖析Numpy中的np.diag源代码
AlphaFold又放大招,剑指整个生物界!
Verilog's random number system task----$random
How to technically ensure the quality of LED display?
The 38-year-old daughter is not in love and has no stable job, the old mother is crying
The sitcom "Re-Walking the Long March" was staged
行为型模式-策略模式
Multithreading (Basic) - 40,000 word summary
多线程之生产者与消费者
ASP.NET Core 6框架揭秘实例演示[31]:路由&quot;高阶&quot;用法
暑期总结3
[Science of Terminology] For those difficult words about the integrated workbench, read this article to understand in seconds!
LayaBox---TypeScript---Decorator
注意力机制
利用二维数据学习纹理三维网格生成(CVPR 2020)
LayaBox---TypeScript---Symbols
bgp与mpls综合实验
SQL 经典50题(题目+解答)(1)
LayaBox---TypeScript---Advanced Type