是否有必要取消订阅

时间:2015-08-24 20:14:53

标签: android rx-java rx-android

我很难理解RX。在下列情况下,是否有必要取消订阅?有没有办法在"电话"之后自动取消订阅?功能被执行了?

Observable.create(new Observable.OnSubscribe<NumberInfo>() {
        @Override
        public void call(Subscriber<? super NumberInfo> subscriber) {
            try {
                // Store data to db
            } catch (Exception e) {
                Log.e(TAG, "Downloaded numberInfo was not added to cache.", e);
            }
        }
    }).subscribeOn(Schedulers.newThread())
    .subscribe(); 

我不想观察任何结果,这就是为什么我省略了经典.observeOn(AndroidSchedulers.mainThread())

感谢解释。

1 个答案:

答案 0 :(得分:5)

根据Rx合约,当Observable触发onCompleted时,Observer取消订阅。在您的情况下,合同不受尊重,因为您的代码中没有subscriber.onCompleted()

如果你只需要像#34; Fire and forget&#34;那么你可以试试:

Schedulers.io().createWorker().schedule(new Action0() {
    @Override
    public void call() {
        try {
            // Store data to db
        } catch (Exception e) {
            Log.e(TAG, "Downloaded numberInfo was not added to cache.", e);
        }
    }
});

它将在 I / O 计划程序上执行,您的UI线程是安全的。

IMO你应该总是有一个返回值。您的Store data to db路由肯定会有一些返回值,例如long指定行号或boolean表示成功。有了这种方法,您就可以创建一个合适的方法:

public Observable<Long> storeToDb(final SomethingToStore storeMe) {
    return Observable
            .create(new Observable.OnSubscribe<Long>() {
                @Override
                public void call(Subscriber<? super Long> subscriber) {
                    long row = syncStore(storeMe);

                    if (row == -1) {
                        subscriber.onError(new Throwable("Cannot store " + storeMe.toString + " to DB."));
                    }

                    subscriber.onNext(row);
                    subscriber.onCompleted();
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

你可以像这样使用它:

storeToDb(storeThis)
        .subscribe(new Observer<Long>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.e("STORING", "Something went south: " + e.getMessage());
            }

            @Override
            public void onNext(Long row) {
                Log.d("STORING", "Everything has been stored as record number: " + row);
            }
        });