Buffer
对信息源的缓存,有重组功能
- 固定大小buffer
buffer 还有其他重载函数,功能都类似,自己摸索 ,
Observable.range(1, 100).buffer(5).subscribe { println("it is $it") }
/**打印
it is [1, 2, 3, 4, 5]
it is [6, 7, 8, 9, 10]
it is [11, 12, 13, 14, 15]
it is [16, 17, 18, 19, 20]
it is [21, 22, 23, 24, 25]
it is [26, 27, 28, 29, 30]
it is [31, 32, 33, 34, 35]
it is [36, 37, 38, 39, 40]
it is [41, 42, 43, 44, 45]
it is [46, 47, 48, 49, 50]
it is [51, 52, 53, 54, 55]
it is [56, 57, 58, 59, 60]
it is [61, 62, 63, 64, 65]
it is [66, 67, 68, 69, 70]
it is [71, 72, 73, 74, 75]
it is [76, 77, 78, 79, 80]
it is [81, 82, 83, 84, 85]
it is [86, 87, 88, 89, 90]
it is [91, 92, 93, 94, 95]
it is [96, 97, 98, 99, 100]
*/
- 基于时间的缓存
当使用interval 方法时,可以试一试,下例将时间事件缓存为一秒钟为单位的数组中
Observable
.interval(200, TimeUnit.MILLISECONDS)
.map { (it + 1) * 100 }
.buffer(1, TimeUnit.SECONDS)
.subscribe { println("$it") }
Thread.sleep(Long.MAX_VALUE)
上面这种情况,可以利用observable 改下,这看上去更为方面
var buffer = Observable.interval(1, TimeUnit.SECONDS)
Observable
.interval(200, TimeUnit.MILLISECONDS)
.map { (it + 1) * 100 }
.buffer(buffer)
.subscribe { println("$it") }
学完缓存,我个人感受就是,把一个分散的东西进行分组管理,这样理解更为容易,处理起来更有调理。
window
和buffer 一样 都是作为缓存而存在,但是有一点区别,就是他返回的是Observable<Observable<T>> ,包含有observable,
Observable
.interval(200, TimeUnit.MILLISECONDS)
.window(1, TimeUnit.SECONDS)
.flatMapSingle {
it.reduce("") { x, y ->
"x= $x ,y = $y"
}
}.subscribe { println(it) }
Thread.sleep(Long.MAX_VALUE)