rxjava的observable订阅时如何实现oncomplete取消订阅

使用rxjava 2.x时,要在oncomplete被调用时取消订阅,可以使用completablefuture.complete向调用方发送完成信号。

示例:

flowable由持久层方法返回,以下是调用方中的代码:

立即学习“Java免费学习笔记(深入)”;

...
private volatile completablefuture future = new completablefuture<>();
private atomicinteger count = new atomicinteger(0);
@override
public disposable flush(information information, flowable table) throws schemaexportexception {
    logger.info("start flowable flush");
    disposable export_flush_complete = table.subscribe(tableins -> {
        system.out.println(printasciitable(tableins));
        system.out.println(printasciicolumns(tableins.getcolumns()));
        system.out.println("
");
        count.addandget(1);
    }, throwable -> {
        logger.debug("export break, reason: " + throwable.getmessage());
        future.cancel(true);
        throw new schemaexportexception(throwable);
    }, new action() {
        @override
        public void run() throws exception {
            logger.debug("export complete, affect size:" + count.get());
            future.complete("ok");
        }
    });
    return export_flush_complete;
}
... 登录后复制 

调用方的代码:

...
    long startStamp = System.currentTimeMillis();
    // Flowable
    Flowable
tableFlowable = result.getAll(dbName.get(), strategy).flatMap(new Function
>() { @Override public Publisher
apply(@NonNull Table table) throws Exception { return result.getTableColumn(table).flatMap(new Function, SingleSource
>() { @Override public SingleSource
apply(@NonNull List columns) throws Exception { return Single.just(table.fillColumn(columns)); } }).flatMapPublisher(new Function
>() { @Override public Publisher<? extends Table> apply(@NonNull Table table) throws Exception { return Flowable.just(table); } }); } }); Disposable disposable = null; try { disposable = out.flush(info, tableFlowable); CompletableFuture future = out.getFuture(); while (!future.isDone()) { logger.info("[ERE-Flowable]未完成,线程休眠1秒"); Thread.currentThread().sleep(1000, 0); } String result = future.get(); logger.info("[ERE-Flowable]完成, 结果:" + result); if (result.equals("OK")) { long finishStamp = System.currentTimeMillis(); clearHander(disposable, "[ERE-Flowable]RxJava disposed because complete, WithTime: " + (finishStamp - startStamp)); } } catch (Exception e) { clearHander(disposable, "[ERE-Flowable]RxJava disposed has Exception: " + e.getMessage()); } ... 登录后复制

以上就是RxJava2.x中,如何优雅地在Observable的onComplete回调后取消订阅?的详细内容,更多请关注慧达安全导航其它相关文章!

点赞(0)

评论列表 共有 0 条评论

暂无评论