Skip to content

Instantly share code, notes, and snippets.

@odbol
Created February 17, 2025 02:33
Show Gist options
  • Save odbol/20de75aff4d0175c79cc5d0e5dda0ed1 to your computer and use it in GitHub Desktop.
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
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