rxjava的observable订阅时在oncomplete被调用时取消订阅

在非android环境中使用rxjava2.x时,如果需要在observable的oncomplete被调用时取消订阅,可以采用以下方法:

在oncomplete中设置completablefuture.complete通知调用方已结束:

table.subscribe(tableins -> {
            // system.out.println("-------information-------");
            system.out.println(tableins);
        }, throwable -> {
            throw new schemaexportexception(throwable);
        }, new action() {
            @override
            public void run() throws exception {
                system.out.println("complete");
                // 在这里取消订阅
                completablefuture.complete();
            }
        });
登录后复制

调用方可以根据completablefuture来判断observable是否已完成:

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

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 条评论

暂无评论