1

処理が遅くなる可能性のある画像を処理するクラスがあります。作業が完了すると、ドミナント カラーなど、画像に関するいくつかの機能がクラスに含まれます。

ドミナントカラーを知りたいコードは他にもたくさんありますが、要求されたときに、準備ができている場合とそうでない場合があります。

RxJava2 を使用してこれを実装する簡単な方法をまだ見つけていません。誰かが私を助けることができますか?

要約すると、次のメソッドを作成できればいいのですが。

  1. 複数のサブスクライバーが通話/サブスクライブできるようにします。
  2. 処理が完了すると、サブスクライバーは結果を受け取ります。
  3. サブスクライバは、メモリ リークを避けるために、自動的に添字が解除されます。2 回目のイベントはありません。また、引き続き購読する理由はありません。
  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 に答える