Skip to content

repeatOnLifecycle #71

Discussion options

You must be logged in to vote

This is just from the top of my head, but I guess it should work.

fun <T> Flow<T>.flowWithLifecycle(
    lifecycle: Lifecycle,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
): Flow<T> {
    require(minActiveState !== Lifecycle.State.INITIALIZED) {
        "flowWithLifecycle cannot start work with minActiveState = Lifecycle.State.INITIALIZED"
    }

    return callbackFlow {
        val scope = CoroutineScope(Dispatchers.Main.immediate)

        var job: Job? = null

        fun start() {
            job = scope.launch { collect { send(it) } }
        }

        fun stop() {
            job?.cancel()
            job = null
        }

        when (minActiveState) {
       …

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@Muhammadali143904
Comment options

Answer selected by Muhammadali143904
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants