Created
April 16, 2024 17:49
-
-
Save morj/3406caf187b42336298faacb58f0147c to your computer and use it in GitHub Desktop.
Primitive flow
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
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