RxJava Observable在异步调用中创建的替代方法

时间:2016-04-21 09:26:37

标签: java rx-java observable frp

我听了这个演讲 https://www.youtube.com/watch?v=QdmkXL7XikQ&feature=youtu.be&t=274

并且我应该避免使用create方法创建一个Observable,因为它不会自动处理取消订阅和背压,但我找不到在下面的代码中使用的替代方法。

compositeSubscription.add(
    Observable.create(new Observable.OnSubscribe<DTOCompaniesCallback>() {
        @Override
        public void call(final Subscriber<? super DTOCompaniesCallback> subscriber) {

            modelTrainStrike.getCompaniesFromServer(new CompaniesCallback() {
                @Override
                public void onResult(DTOCompaniesCallback dtoCompaniesCallback) {
                    try {
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onNext(dtoCompaniesCallback);
                            subscriber.onCompleted();
                        }
                    } catch (Exception e) {
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onError(e);
                        }
                    }
                }
            });

        }
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<DTOCompaniesCallback>() {
        @Override
        public void call(DTOCompaniesCallback dtoCompaniesCallback) {
            Log.i("TAG", "onResult: " + dtoCompaniesCallback.getCompaniesList().size());
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            throw new OnErrorNotImplementedException("Source!", throwable);
        }
    })
);

我在OnDestroy方法中调用了CompositeSubscription

@Override
public void onDestroy() {
    if (compositeSubscription != null) {
        compositeSubscription.clear();
    }
}

您是否看到了我可以在此处使用的创建方法的替代方法? 您是否看到任何潜在的危险或这种方法是否安全? 感谢

1 个答案:

答案 0 :(得分:6)

您可以使用defer + AsyncSubject:

Observable.defer(() -> {
    AsyncSubject<DTOCompaniesCallback> async = AsyncSubject.create();
    modelTrainStrike.getCompaniesFromServer(v -> {
        async.onNext(v);
        async.onComplete();
    });
    return async;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
...

如果getCompaniesFromServer支持取消,您可以:

Observable.defer(() -> {
    AsyncSubject<DTOCompaniesCallback> async = AsyncSubject.create();
    Closeable c = modelTrainStrike.getCompaniesFromServer(v -> {
        async.onNext(v);
        async.onComplete();
    });
    return async.doOnUnsubscribe(() -> {
        try { c.close(); } catch (IOException ex) { }
    });
})