简体   繁体   中英

How to process all events of Observable in one thread, but get the latest value available in another thread in Rxjava?

I am using RxJava2 in Android and I have the below problem, but it's not specific to Android.

I have a PublishSubject to push all my events. I call publishSubject.onNext() in multiple parts of my code based on different events. But I have a central place in my code where I subscribe to these events. The below is the subscription code:

publishSubject
    .observeOn(Schedulers.computation())
    .map(
        // each computation takes about 10ms
        // Do some computation and return a `computation` object
    )
    .observerOn(AndroidSchedulers.mainThread())
    .subscribe(
        // take the `computation` object and draw on screen
        // each drawing takes about 100ms
    );

Now, in the above case, if I call publishSubject.onNext() 100 times, then computation will be done 100 times and drawing on screen will be done 100 times.

The thing is I care about the 100 times computation. Every event has to be computed. But not every computed object needs to be drawn.

When the 1st computation object is being drawn on screen it takes 100ms to draw in MAIN thread, but by that time 10 new computation objects are generated in COMPUTATION thread. So the 2nd time I draw on the screen I don't want to draw the 2nd computation object, but rather the latest computation object available for me (probably the 11th computation object).

In short, I am looking for a way to do all computation all the time, but draw on screen only the latest computation object available at that time.

Have you tried something like this?

publishSubject
.observeOn(Schedulers.computation())
.map(...)
.toFlowable(BackpressureStrategy.LATEST)
.observerOn(AndroidSchedulers.mainThread())
.subscribe(...);

This will make sure that the computation actually happens, but the subscription will not receive items that are too far back in time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM