.subscribeOn()方法无法识别

时间:2018-07-17 08:59:31

标签: android rx-java rx-java2 rx-android

我想在我的项目中使用RxAndroid和RxJava。因此,在build.gradle文件中添加了如下所示的行。但是,当我尝试使用

            animalsObserver.subscribeOn();//unrecognized

AndroidStudio无法识别它。因此,请让我知道如何正确使用.subscribeOn()方法。

代码

import rx.Observable;
import rx.Observer;

public class MainActivity extends AppCompatActivity {
    Observable<String> animalsObservable = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        animalsObservable = Observable.just("Ant", "Bee", "Cat", "Dog", "Fox");
        Observer<String> animalsObserver = getAnimalsObserver();
        animalsObserver.subscribeOn();//unrecognized
    }

    private Observer<String> getAnimalsObserver() {
        return new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, "onSubscribe");
            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "Name: " + s);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "All items are emitted!");
            }
        };
    }
}

等级

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.9'
testCompile 'junit:junit:4.12'

}

3 个答案:

答案 0 :(得分:1)

具有Observable API而不是subcribeOn()的{​​{1}}。您的示例应类似于:

Observer

答案 1 :(得分:0)

在subscribeOn()方法中,您必须传递将在其上执行观察者的调度程序 您需要 subscribe()方法;

答案 2 :(得分:0)

在Observable而不是Observer上调用方法subsribeOn()。因此,如下修改您的代码:

animalsObservable
.subscribeOn(Scheduler.io()) //run on background thread
.observerOn(AndroidScheduler.mainThread())
.subscribe(animalsObserver);