RxJava: how do you flush a timed buffer?

ⅰ亾dé卋堺 提交于 2021-01-28 08:46:00

问题


I'm creating this PublishProcessor that save to the database its element every 10 seconds:

    val publishProcessor = PublishProcessor.create<Entity>()

    publishProcessor
        .buffer(10, SECONDS)
        .observeOn(Schedulers.io())
        .subscribe(
            { saveToDatabase(it) },
            { Log.e("TAG", "Error: $it") })
        .addTo(compositeDisposable)

When my activity finish, I want to flush everything that is in the current buffer, and not wait 10 seconds. How do I do that?


回答1:


Have another subject as the buffer boundary that is merged with an interval:

PublishSubject<Entity> publishProcessor = PublishSubject.create();

Subject<Long> flush = PublishSubject.<Long>create().toSerialized();

publishProcessor
    .buffer(flush.mergeWith(Observable.interval(10, TimeUnit.MILLISECONDS)))
    .observeOn(Schedulers.io())
    .subscribe(...)

flush.onNext(1L);

If you want to also reset the timer upon a manual flush

publishProcessor
    .buffer(
        flush.mergeWith(Observable.timer(10, TimeUnit.MILLISECONDS))
        .take(1)
        .repeat()
    )
    .observeOn(Schedulers.io())
    .subscribe(...)


来源:https://stackoverflow.com/questions/55870523/rxjava-how-do-you-flush-a-timed-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!