RxJava android - 观察者阻止

时间:2015-01-21 15:57:51

标签: android observer-pattern rx-java

鉴于这个简单的观察者和订阅者组合,它只是观察文件IO,然后根据值更新订阅者:

Observable.just(preferences.getBoolean(C"vibrate", false))
            .subscribeOn(Schedulers.io())//observe on new thread
            .observeOn(AndroidSchedulers.mainThread()) //subscribe(listen) on main thread
            .subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean shouldVibrate) {
                    if (shouldVibrate)
                        Toast.makeText(context,"i should vibrate now",Toast.SHORT).show();
                }

            });

我的问题是,观察者会阻止写入完成吗?即使我指定了另一个线程(IO线程),这个观察者是否仍会阻止订阅者调用一次?

1 个答案:

答案 0 :(得分:1)

在您订阅Observer之前,您的Observer胜利阻止了您的操作(因此,它只会发出您的价值)

关于你的代码(简单来说就是java 8样式):

Observable.just(preferences.getBoolean("vibrate", false))
        .subscribeOn(Schedulers.io())//observe on new thread
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(shouldVibrate) -> {
                if (shouldVibrate) {
                    Toast.makeText(context,"i should vibrate now",Toast.SHORT).show();
                }
        });

您可以将调用解压缩为变量preferences.getBoolean(C"vibrate", false)

Boolean vibrate = preferences.getBoolean("vibrate", false);
Observable.just(vibrate)
        .subscribeOn(Schedulers.io())//observe on new thread
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(shouldVibrate) -> {
                if (shouldVibrate) {
                    Toast.makeText(context,"i should vibrate now",Toast.SHORT).show();
                }
        });

如您所见,vibrate将在之前计算,然后主线程将被阻止。

你应该写一个&#34; lazy&#34;使用Observable.create方法

调用您的方法
Observable.create(sub -> {
              Boolean vibrate = preferences.getBoolean("vibrate", false);
              sub.onNext(vibrate);
              sub.onCompleted();

         })
        .subscribeOn(Schedulers.io())//observe on new thread
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(shouldVibrate) -> {
                if (shouldVibrate) {
                    Toast.makeText(context,"i should vibrate now",Toast.SHORT).show();
                }
        });

使用此代码,只有当您订阅Boolean vibrate = preferences.getBoolean("vibrate", false);时才会调用Observer

(关于您的if,在您的订阅者中,您可以使用filter更改

        Observable.create(sub -> {
              Boolean vibrate = preferences.getBoolean("vibrate", false);
              sub.onNext(vibrate);
              sub.onCompleted();

         })
        .filter((value) -> value)
        .subscribeOn(Schedulers.io())//observe on new thread
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(shouldVibrate) -> {
                    Toast.makeText(context,"i should vibrate now",Toast.SHORT).show();
        });