開始:
編寫文件 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)
}
}
運(yùn)行一下:
1
2
3
Process finished with exit code 0
Down邑茄,寫完了!
太簡單了慨蛙,再送一個(gè)操作符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)
}
}
運(yùn)行一下:
print: 1
print: 2
print: 3
Process finished with exit code 0