Skip to content

Instantly share code, notes, and snippets.

@morj
Created April 16, 2024 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morj/3406caf187b42336298faacb58f0147c to your computer and use it in GitHub Desktop.
Save morj/3406caf187b42336298faacb58f0147c to your computer and use it in GitHub Desktop.
Primitive flow
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
interface Flow<out T> {
suspend fun collect(collector: FlowCollector<T>)
}
fun interface FlowCollector<in T> {
suspend fun emit(value: T)
}
fun <T> primitiveFlow(block: suspend FlowCollector<T>.() -> Unit): Flow<T> = object : Flow<T> {
override suspend fun collect(collector: FlowCollector<T>) = block(collector)
}
fun main() = runBlocking {
val counter = AtomicInteger(0)
val flow = primitiveFlow {
counter.incrementAndGet()
emit("a")
emit("b")
emit("c")
}
flow.collect {
println(it)
}
println("Flow was collected ${counter.get()} time")
flow.collect {
println(it)
}
println("Flow was collected ${counter.get()} times")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment