File tree Expand file tree Collapse file tree
app/src/main/java/org/ninetripods/mq/study/kotlin Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -131,7 +131,8 @@ class FlowStudyActivity : BaseActivity() {
131131 mTvConvertSF.text = builder.toString()
132132 }
133133 }
134- // NOTE:跟Flow.flowWithLifecycle效果一致
134+ // 1、可以把这里通过扩展函数进行封装 如:mFlowModel.flowConvertStateFlow.launchAndCollectIn(this) {}
135+ // 2、NOTE:跟Flow.flowWithLifecycle效果一致
135136// mFlowModel.flowConvertStateFlow
136137// .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
137138// .collect {
Original file line number Diff line number Diff line change 11package org.ninetripods.mq.study.kotlin.ktx
22
3- import androidx.lifecycle.LifecycleOwner
4- import androidx.lifecycle.LiveData
3+ import androidx.fragment.app.Fragment
4+ import androidx.lifecycle.*
5+ import kotlinx.coroutines.CoroutineScope
6+ import kotlinx.coroutines.flow.Flow
7+ import kotlinx.coroutines.flow.collect
8+ import kotlinx.coroutines.launch
59
610/* *
711 * LiveData扩展函数封装
812 */
913fun <T > LifecycleOwner.observe (liveData : LiveData <T >, observer : (t: T ) -> Unit ) {
1014 liveData.observe(this , { observer(it) })
1115}
16+
17+ /* *
18+ * repeatOnLifecycle: https://juejin.cn/post/7001371050202103838
19+ */
20+ inline fun <T > Flow<T>.launchAndCollectIn (
21+ owner : LifecycleOwner ,
22+ minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
23+ crossinline action : suspend CoroutineScope .(T ) -> Unit
24+ ) = owner.lifecycleScope.launch {
25+ owner.lifecycle.repeatOnLifecycle(minActiveState) {
26+ collect {
27+ action(it)
28+ }
29+ }
30+ }
31+
32+ /* *
33+ * Fragment中使用repeatOnLifecycle
34+ */
35+ inline fun Fragment.launchAndRepeatWithViewLifecycle (
36+ minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
37+ crossinline block : suspend CoroutineScope .() -> Unit
38+ ) {
39+ viewLifecycleOwner.lifecycleScope.launch {
40+ viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
41+ block()
42+ }
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments