Flow 和 LiveData 之操作符:throttleFirst、 throttleLast 、throttleLatest、debounce
文章目录
前言
因为使用kotlin 和协程后准备移除RxJava,其中大部分功能,可以使用Flow进行替代,但是出现了部分操作符功能缺少,所有进行改进。
这是一遍没有检验的文章,部分操作操作符只是按逻辑写的,没有测试。有几个只是按自己的需求写的,可能和RxJava的存在差异
一、Flow 之操作符扩展
1. ThrottleFirst
fun <T> Flow<T>.throttleFirst(duration: Long = 1000L) = this.throttleFirstImpl(duration)
fun <T> Flow<T>.throttleFirstImpl(periodMillis: Long): Flow<T> {
return flow {
var lastTime = 0L
collect {
value ->
val currentTime = System.currentTimeMillis()
if (currentTime - lastTime >= periodMillis) {
lastTime = currentTime
emit(value)
}
}
}
}
2. ThrottleLast
fun <T> Flow<T>.throttleLast(duration: Long = 1000L) = this.sample(duration)
3. ThrottleLatest
fun <T> Flow<T>.throttleLatest(duration: Long = 1000L) = this.throttleLatestImpl(duration)
internal fun <T> Flow<T>.throttleLatestImpl(periodMillis: Long): Flow<T> {

本文介绍了如何在Flow和LiveData中扩展使用throttleFirst、throttleLast、throttleLatest和debounce操作符,以优化数据流处理。通过自定义实现,作者针对kotlin协程和LiveData场景提供了这些功能的替代解决方案。
最低0.47元/天 解锁文章
426

被折叠的 条评论
为什么被折叠?



