将异步计算的数据传播回 GUI 线程

Propagating asynchronously calculated data back to the GUI thread

我实施了一项服务,该服务可从眼动仪异步获取数据并提供一个 PublishSubject,任何有兴趣的人都可以订阅该服务以获取最新的眼动仪事件流。

我不知道如何将这些事件放入我的 GUI 线程(因为眼动追踪在没有显示内容的情况下毫无用处)以及如何充分限制接收到的事件以使 GUI 不滞后因为阻塞了线程。

谁能告诉我如何使用 RxJava 做到这一点?

... You can move computations or blocking IO to some other thread via subscribeOn. Once the data is ready, you can make sure they get processed on the foreground or GUI thread via observeOn

响应式扩展提供了一种叫做 Schedulers 的东西。它们指示流更改它们在其上生成或观察项目的线程。您可以通过运算符 subscribeOn 来设置它们,它会修改流,以便您的生产者发出其项目(换句话说,在其订阅者上调用 onNext 方法),或者通过名为 observeOn 的运算符来设置它们告诉流在指定的调度程序上安排其观察工作。

getSomeObservable() // Observable does its work on computation scheduler
    .observeOn(Schedulers.io()) // instructs to switch every afterwards operator to observe items on io scheduler
    .map(...) // this callback is called on a thread provided by io scheduler
    .filter(...) // and this as well
    .observeOn(Schedulers.newThread()) // switch to new thread scheduler
    .doOnNext() // new thread
    .subscribeOn(Schedulers.computation()) // instructs to produce items on computational scheduler
    .subscribe(...) // still scheduling this task to new thread scheduler

通常,对 rx 有一定程度支持的框架有一些在 UI 线程上执行工作的调度程序实现...... Android 例如有一个库提供 AndroidSchedulers.mainThread() 这是正是您要找的,只在您的框架中