如何阻止RXJava 2在第一个错误之后发出更多错误?

时间:2019-04-03 17:12:35

标签: rx-java2 vert.x

使用RX Java 2.2.6。

我了解到,当发出单个错误时,整个流将停止。但是,如果发出多个错误,那么我得到...

The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with.

因此,在以下情况下,我的observable是从逐行发送的文件流中创建的。例如,当myService(http服务)实例关闭时,将发出多个错误。由于多条线路已推向服务。因此,如果文件有10行,则第一个错误将完成可观察项,但随后将发出另外9个错误,但那时可观察项已关闭,我希望将其关闭。

我应该将myService切换为Single而不是Completable吗?

目前,myService基于处理程序,并且说明了为什么我创建了Completable包装器。

observable
  .skipLast(1)
  .map(buffer -> new JsonArray(buffer))
  .flatMap(record ->
    Completable.create(emitter -> {
      if (record.size() > 13) {
        myService.send(..., writeResult -> {
          if (writeResult.succeeded()) {
            emitter.onComplete();
          } else {
            emitter.onError(writeResult.cause());
          }
        });
      } else {
        emitter.onError(new IllegalArgumentException("Record contains invalid amount of elements. Found: " + record.size() + " elements."));
      }
    }).toObservable())
  .doOnComplete(() -> {
    resultHandler.handle(Future.succeededFuture(successCount.longValue()));
  }).subscribe(
  o -> {
  },
  t -> {
    resultHandler.handle(Future.failedFuture(t));
  });

更新:检查发射器是否被处置似乎可以解决问题?

observable
.skipLast(1)
.map(buffer -> new JsonArray(buffer.getDelegate()))
.flatMap(record ->
  Completable.create(emitter -> {

          myService.send(..., writeResult -> {
            if (writeResult.succeeded()) {
              successCount.getAndIncrement();

              if (!emitter.isDisposed())
                emitter.onComplete();
            } else {
              if (!emitter.isDisposed())
                emitter.onError(writeResult.cause());
            }
          });
        } else {
          if(!emitter.isDisposed())
            emitter.onError(new IllegalArgumentException("Invalid topic."));
        }
  }).toObservable())
.doOnComplete(() -> {
  resultHandler.handle(Future.succeededFuture(successCount.longValue()));
}).subscribe(
o -> {
  // Do nothing
},
t ->
  resultHandler.handle(Future.failedFuture(new IllegalStateException("Failed at line: " + successCount.get(), t)))
);

1 个答案:

答案 0 :(得分:0)

我相信flatMapCompletable可以达到目的:

fun observeRecordings(): Observable<Unit> =
        Observable.just(20)
                .skipLast(1)
                .map { JsonArray(it) }
                .filter { it.size() > 13 }
                .flatMapCompletable { service.send(it) }
                .doOnError { }
                .toObservable()

抱歉使用Kotlin!