2022-11-12 给大家徒手写个Flow

开始:

编写文件 RFlow.kt:

package rflow


/**
 * @author  reone
 * @date    2022/11/12 15:03
 * description:
 */

fun interface RFlowCollector {
    fun emit(value: T)
}

interface RFlow {
    fun collect(collector: RFlowCollector)
}

fun  rflow(flowBlock: RFlowCollector.() -> Unit): RFlow {
    return object : RFlow {
        override fun collect(collector: RFlowCollector) {
            collector.flowBlock()
        }
    }
}

编写测试用例 Main.kt:

package rflow

fun main(args: Array) {
    rflow {
        emit(1)
        emit(2)
        emit(3)
    }.collect {
        println(it)
    }
}

运行一下:

1
2
3

Process finished with exit code 0

Down,写完了!

太简单了,再送一个操作符map:

fun  RFlow.map(mapBlock: (value: T) -> R): RFlow {
    return rflow {
        collect { value ->
            emit(mapBlock.invoke(value))
        }
    }
}

修改测试用例:

package rflow

fun main(args: Array) {
    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

Down,又写完了

你可能感兴趣的:(2022-11-12 给大家徒手写个Flow)