@@ -5,17 +5,31 @@ import androidx.fragment.app.FragmentActivity
55import androidx.lifecycle.Lifecycle
66import androidx.lifecycle.lifecycleScope
77import kotlinx.coroutines.CoroutineScope
8+ import kotlinx.coroutines.Dispatchers
89import kotlinx.coroutines.launch
10+ import kotlin.coroutines.CoroutineContext
911
1012/* *
11- * Launches a new coroutine and repeats `block` every time the Fragment's viewLifecycleOwner
12- * is in and out of `minActiveState` lifecycle state.
13+ * 更加简洁的语法封装
14+ *
15+ * 在 [Fragment.getViewLifecycleOwner] 达到 [minActiveState] 时,启动一个新的协程并重复 [block] 并在 [Lifecycle.Event.ON_DESTROY] 时,取消协程。
16+ *
17+ * 警告:不要在其他 CoroutineScope 中调用本函数!!!
18+ *
19+ * 如果在 CoroutineScope 中调用本函数,会隐式持有外部作用域
20+ *
21+ * 但是并不会保留外部作用域的上下文,也就是无法实现结构化并发
22+ *
23+ * @param newCoroutineContext 协程上下文 默认 [Dispatchers.Main]
24+ * @param minActiveState 需要达到的最小生命周期状态 默认 [Lifecycle.State.STARTED]
25+ * @param block 协程代码块
1326 */
1427inline fun Fragment.launchAndRepeatWithViewLifecycle (
28+ newCoroutineContext : CoroutineContext = Dispatchers .Main ,
1529 minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
1630 crossinline block : suspend CoroutineScope .() -> Unit
1731) {
18- viewLifecycleOwner.lifecycleScope.launch {
32+ viewLifecycleOwner.lifecycleScope.launch(newCoroutineContext) {
1933 viewLifecycleOwner.lifecycle.repeatOnLifecycle(minActiveState) {
2034 block()
2135 }
@@ -25,20 +39,24 @@ inline fun Fragment.launchAndRepeatWithViewLifecycle(
2539/* *
2640 * 更加简洁的语法封装
2741 *
42+ * 在 [FragmentActivity.getLifecycle] 达到 [minActiveState] 时,启动一个新的协程并重复 [block] 并在 [Lifecycle.Event.ON_DESTROY] 时,取消协程。
43+ *
2844 * 警告:不要在其他 CoroutineScope 中调用本函数!!!
2945 *
3046 * 如果在 CoroutineScope 中调用本函数,会隐式持有外部作用域
3147 *
3248 * 但是并不会保留外部作用域的上下文,也就是无法实现结构化并发
3349 *
34- * @param minActiveState 需要达到的最小生命周期状态
50+ * @param newCoroutineContext 协程上下文 默认 [Dispatchers.Main]
51+ * @param minActiveState 需要达到的最小生命周期状态 默认 [Lifecycle.State.STARTED]
3552 * @param block 协程代码块
3653 */
3754inline fun FragmentActivity.launchAndRepeatWithViewLifecycle (
55+ newCoroutineContext : CoroutineContext = Dispatchers .Main ,
3856 minActiveState : Lifecycle .State = Lifecycle .State .STARTED ,
3957 crossinline block : suspend CoroutineScope .() -> Unit
4058) {
41- lifecycleScope.launch {
59+ lifecycleScope.launch(newCoroutineContext) {
4260 lifecycle.repeatOnLifecycle(minActiveState) {
4361 block()
4462 }
0 commit comments