Kotlin 系列 之 Flow(二)中间运算符

4 篇文章 0 订阅
3 篇文章 1 订阅

Hello I`am Flow ,Welcome to Flow Unit 2

说到 中间运算符 ,用过 RxJava 的同学可能会想,难道是命运的安排 ?

我想说:这就是命啊!~ 他两的关系就是 (PX剑谱 和 KH宝典)

PS:Flow 的中间 运算符内的代码块 是可以 调用挂起函数

Example 1 (耳熟能详的 map 、filter)

map :对结果进行加工后继续向后传递

filter : 对待操作的值 进行过滤

private suspend fun myMapFun(input:Int): String {
    delay(1000)
    return "output: $input"
}

fun main() = runBlocking {
    (1..4).asFlow()
        .filter{ it > 2}
        .map{input-> myMapFun(input)}
        .collect{ println(it)}

}

结果打印:		"output: 3"  
				"output: 4"
Example 2 (清清白白的 tranform)

上面的mapfilter 都有自身特定的功能(小爷我干这活贼6,但是别的不会 - -!)

transform :没有附加功能,白纸一张,码农咋写 咱咋发射。

private suspend fun myFun(input:Int): String {
    delay(1000)
    return "output: $input"
}

fun main() = runBlocking {
    (1..2).asFlow()
        .transform{input ->
            emit("hello $input")
            emit("world $input")
            emit(myFun(input))
        }
        .collect{ println(it)}

}
结果打印:		"hello: 1"  
				"world: 1"
				"output: 1"

				"hello: 2"  
				"world: 2"
				"output: 2"

Example 2 (适可而止的 take)

take 会限制 emit() 发射的次数 (你想发射就发射?)

PS:take 的入参 <= emit 发射的次数时,会抛出异常

fun myNumber() = flow {
    try {
        emit(1)
        println("hello")
        emit(2)
        println("world")
        emit(3)
    }catch (ex:Exception){
        println(ex)
    }finally {
        println("finally")
    }
}

fun main() = runBlocking {
    myNumber().take(2).collect{ println(it)}
}

结果打印:		"1"
				"hello"
				"2"
				"kotlinx.coroutines.flow.internal.AbortFlowException:....."
				"finally"
collect 之外的【终止操作】

终止操作:才会真正的执行 flow

有 collect 、toList、toSet、count、reduce、collectLatest 等

下面 挑两个 look look ;

Example 3 (葫芦娃合体的 reduce)

reduce 让结果之间再次运算

fun main() = runBlocking {
    var result3= (1..7).asFlow()
        .map{ it * 1 }
        .reduce{a,b -> a + b}
    println(result3)
  
  打印结果:28 // 从 1 加到 7
}
Example 4 (说打就打的 collectLatest)

collectLatest collectLatest块中的执行时间大于emit发射的间隔时间,那么将会被emit 打断

emit:(这货话太多了)不好意思我插一句!!

官方栗子:

flow {
     emit(1)
     delay(50)
     emit(2)
 }.collectLatest { value ->
     println("Collecting $value")
     delay(100) // Emulate work
     println("$value collected")
 }
结果打印:	"Collecting 1" 
		    "Collecting 2" 
		    "2 collected"

还有很多操作大家可以探索一下 欢迎评论区留言 !~~

小结:本次介绍了一些常用的 中间运算符终止操作 下一节 Flow(三)执行顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值