1

我有一个处理图像的类,这可能是一个缓慢的过程。工作完成后,该类包含有关图像的一些特征,例如主色。

我有很多其他的代码想要知道主色,当他们请求它时,它可能准备好也可能还没有准备好。

我还没有找到一种使用 RxJava2 来实现它的简单方法。有人能帮我吗?

总而言之,如果我可以创建一个方法,那就太好了:

  1. 允许多个订阅者呼叫/订阅。
  2. 处理完成后,订阅者会收到结果。
  3. 订阅者会自动取消订阅以避免内存泄漏。不会有第二个事件,也没有理由仍然被订阅。
  4. 稍后订阅/调用该方法的订阅者只会获取缓存的值。

ReplaySubject 似乎有一些我正在寻找的属性,但我不确定如何正确实现它。

4

1 回答 1

0

'1. Allows multiple subscribers to call/subscribe to.
'4. Subscribers which subscribe/call the method at a later point just gets the the cached value.

Use replay(1) in combination with autoConnect(). This will result in an observable that shares a single subscription to the source, and replays the last value emitted by the source. autoConnect() ensures that the source is directly subscribed to when the first subscriber subscribes.

  1. When the processing is done, the subscribers receives the result.

Use Observable.create() and use the ObservableEmitter to emit the result.

  1. The subscribers are automatically unsubscripted to avoid memory leaks. There will be no second event, and no reason to still be subscribed.

Convert the Observable to a Single.


Something along the lines of the following should work:

Observable.create(new ObservableOnSubscribe<String>() {
  @Override
  public void subscribe(final ObservableEmitter<String> e) throws Exception {
    Thread.sleep(5000);
    e.onNext("Test");
    e.onComplete();
  }
}).replay(1).autoConnect()
    .firstOrError();

Note that you should keep a reference to this Observable (the result of firstOrError()) and share that instance with the subscribers.

于 2016-11-28T14:48:14.977 回答