1
1
package com.monstarlab.extensions
2
2
3
3
import androidx.fragment.app.Fragment
4
+ import androidx.lifecycle.DefaultLifecycleObserver
5
+ import androidx.lifecycle.LifecycleOwner
4
6
import androidx.lifecycle.lifecycleScope
5
7
import kotlinx.coroutines.flow.Flow
6
8
import kotlinx.coroutines.flow.collect
@@ -9,13 +11,27 @@ import kotlinx.coroutines.flow.zip
9
11
import kotlinx.coroutines.launch
10
12
11
13
fun <T > Fragment.collectFlow (targetFlow : Flow <T >, collectBlock : ((T ) -> Unit )) {
12
- viewLifecycleOwner.lifecycleScope.launchWhenCreated {
13
- targetFlow.collect {
14
- collectBlock.invoke(it)
14
+ safeViewCollect {
15
+ viewLifecycleOwner.lifecycleScope.launchWhenCreated {
16
+ targetFlow.collect {
17
+ collectBlock.invoke(it)
18
+ }
15
19
}
16
20
}
17
21
}
18
22
23
+ private inline fun Fragment.safeViewCollect (crossinline viewOwner : LifecycleOwner .() -> Unit ) {
24
+ lifecycle.addObserver(object : DefaultLifecycleObserver {
25
+ override fun onCreate (owner : LifecycleOwner ) {
26
+ viewLifecycleOwnerLiveData.observe(
27
+ this @safeViewCollect,
28
+ { viewLifecycleOwner ->
29
+ viewLifecycleOwner.viewOwner()
30
+ })
31
+ }
32
+ })
33
+ }
34
+
19
35
fun <T1 , T2 > Fragment.combineFlows (flow1 : Flow <T1 >, flow2 : Flow <T2 >, collectBlock : ((T1 , T2 ) -> Unit )) {
20
36
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
21
37
flow1.combine(flow2) { v1, v2 ->
0 commit comments