开始:
编写文件 RFlow.kt:
package rflow
/**
* @author reone
* @date 2022/11/12 15:03
* description:
*/
fun interface RFlowCollector<T> {
fun emit(value: T)
}
interface RFlow<T> {
fun collect(collector: RFlowCollector<T>)
}
fun <T> rflow(flowBlock: RFlowCollector<T>.() -> Unit): RFlow<T> {
return object : RFlow<T> {
override fun collect(collector: RFlowCollector<T>) {
collector.flowBlock()
}
}
}
编写测试用例 Main.kt:
package rflow
fun main(args: Array<String>) {
rflow {
emit(1)
emit(2)
emit(3)
}.collect {
println(it)
}
}
运行一下:
1
2
3
Process finished with exit code 0
Down,写完了!
太简单了,再送一个操作符map:
fun <T, R> RFlow<T>.map(mapBlock: (value: T) -> R): RFlow<R> {
return rflow {
collect { value ->
emit(mapBlock.invoke(value))
}
}
}
修改测试用例:
package rflow
fun main(args: Array<String>) {
rflow {
emit(1)
emit(2)
emit(3)
}.map {
"print: $it"
}.collect {
println(it)
}
}
运行一下:
print: 1
print: 2
print: 3
Process finished with exit code 0