@@ -4,32 +4,35 @@ import android.util.Log
4
4
import androidx.fragment.app.Fragment
5
5
import androidx.lifecycle.Lifecycle
6
6
import androidx.lifecycle.LifecycleOwner
7
- import androidx.lifecycle.addRepeatingJob
7
+ import androidx.lifecycle.lifecycleScope
8
+ import androidx.lifecycle.repeatOnLifecycle
8
9
import kotlinx.coroutines.Job
9
10
import kotlinx.coroutines.flow.Flow
10
11
import kotlinx.coroutines.flow.collect
11
- import kotlin.coroutines.CoroutineContext
12
- import kotlin.coroutines.EmptyCoroutineContext
12
+ import kotlinx.coroutines.launch
13
13
14
14
inline fun <T > Flow<T>.collectIn (
15
15
owner : LifecycleOwner ,
16
16
minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
17
- coroutineContext : CoroutineContext = EmptyCoroutineContext ,
18
17
crossinline action : suspend (value: T ) -> Unit ,
19
- ): Job = owner.addRepeatingJob(state = minActiveState, coroutineContext = coroutineContext) {
20
- Log .d(" collectIn" , " Start collecting..." )
21
- collect { action(it) }
18
+ ): Job = owner.lifecycleScope.launch {
19
+ owner.repeatOnLifecycle(state = minActiveState) {
20
+ Log .d(" collectIn" , " Start collecting $owner $minActiveState ..." )
21
+ collect { action(it) }
22
+ }
22
23
}
23
24
25
+ /* *
26
+ * Launches a new coroutine and repeats `block` every time the Fragment's viewLifecycleOwner
27
+ * is in and out of `minActiveState` lifecycle state.
28
+ */
24
29
@Suppress(" unused" )
25
- inline fun <T > Flow<T>.collectIn (
30
+ inline fun <T > Flow<T>.collectInViewLifecycle (
26
31
fragment : Fragment ,
27
32
minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
28
- coroutineContext : CoroutineContext = EmptyCoroutineContext ,
29
33
crossinline action : suspend (value: T ) -> Unit ,
30
34
): Job = collectIn(
31
- fragment.viewLifecycleOwner,
35
+ owner = fragment.viewLifecycleOwner,
32
36
minActiveState = minActiveState,
33
- coroutineContext = coroutineContext,
34
37
action = action,
35
38
)
0 commit comments