Created
February 17, 2025 02:33
-
-
Save odbol/20de75aff4d0175c79cc5d0e5dda0ed1 to your computer and use it in GitHub Desktop.
Utils for use coroutines from Java code, like calling Flow.collect() from Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.odbol.coroutines | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.coroutineScope | |
import java.util.function.Consumer | |
import kotlinx.coroutines.flow.StateFlow | |
import kotlinx.coroutines.launch | |
/** Helps using Kotlin coroutines from Java code */ | |
object CoroutineHelper { | |
/** | |
* Allows you to call collect() on a StateFlow from Java code | |
* | |
* @param collector called whenever flow emits a new value | |
*/ | |
fun <T : Any> collect(lifecycle: Lifecycle, flow: StateFlow<T>, collector: Consumer<T>) { | |
lifecycle.coroutineScope.launch { flow.collect { collector.accept(it) } } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment