问题
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