All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.dev.datlag.tooling.decompose.lifecycle.CollectOnLifecycle.kt Maven / Gradle / Ivy

There is a newer version: 1.7.0
Show newest version
package dev.datlag.tooling.decompose.lifecycle

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import com.arkivanov.essenty.lifecycle.Lifecycle
import com.arkivanov.essenty.lifecycle.LifecycleOwner
import dev.datlag.tooling.async.collectSafe
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.callbackFlow

suspend fun  Flow.collectOnLifecycle(
    lifecycle: Lifecycle,
    state: Lifecycle.State = Lifecycle.State.STARTED,
    collector: FlowCollector
) {
    lifecycle.repeatOnLifecycle(state) {
        collectSafe(collector)
    }
}

suspend fun  Flow.collectOnLifecycle(
    lifecycleOwner: LifecycleOwner,
    state: Lifecycle.State = Lifecycle.State.STARTED,
    collector: FlowCollector
) {
    lifecycleOwner.repeatOnLifecycle(state) {
        collectSafe(collector)
    }
}

@Composable
fun  Flow.collectOnLocalLifecycle(
    state: Lifecycle.State = Lifecycle.State.STARTED,
    collector: FlowCollector
) {
    val lifecycle = LocalLifecycleOwner.current
    LaunchedEffect(this, lifecycle) {
        lifecycle.repeatOnLifecycle(state) {
            collectSafe(collector)
        }
    }
}

fun  Flow.flowWithLifecycle(
    lifecycle: Lifecycle,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow = callbackFlow {
    lifecycle.repeatOnLifecycle(minActiveState) {
        [email protected] {
            send(it)
        }
    }
    close()
}

fun  Flow.flowWithLifecycle(
    lifecycle: LifecycleOwner,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow = callbackFlow {
    lifecycle.repeatOnLifecycle(minActiveState) {
        [email protected] {
            send(it)
        }
    }
    close()
}

@Composable
fun  Flow.withLocalLifecycle(
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow {
    val lifecycle = LocalLifecycleOwner.current
    return callbackFlow {
        lifecycle.repeatOnLifecycle(minActiveState) {
            [email protected] {
                send(it)
            }
        }
        close()
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy