RxAndroid 和多线程

RxAndroid and multithreading

我正在使用 RxAndroid 在后台做一些事情。这是我的代码:

Observable<MyClass[]> observable = Observable.create(new Observable.OnSubscribe<MyClass[]>() {

        @Override
        public void call(Subscriber<? super MyClass[]> subscriber) {
                System.out.println(Looper.myLooper() + " - " + Looper.getMainLooper());
                try {
                    MyObject myObject = ...
                    //do the background work
                    subscriber.onNext(myObject);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                    e.printStackTrace();
                }
            }
        });

        observable.subscribeOn(Schedulers.newThread())
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(new Action1<MyClass[]>() {
                      @Override
                      public void call(MyClass[] myObjects) {
                          //do work on the ui Thread
                      }
                  }
        );

这是我第一次使用 RxAndroid / RxJava / Looper.myLooper() / Looper.getMainLooper()

据我所知,Looper.myLooper() 为您提供了当前代码正在运行的线程的名称 ID,运行 为您提供了主线程的 ID。当我 运行 应用程序时,在 SysOut 中,它会为它们打印出相同的 ID。

我是做错了什么还是误解了 2 个 Looper 函数?

建议您不要使用 Observable.create 除非您 真的 知道您在使用 Observables 做什么。有很多事情您可能会出错。

你创建的代码在主线程上 运行 的原因是它在创建 Observable 时被调用 而不是 当你订阅时

对于你想要实现的目标,我会使用 Observable.deferdocs:

The Defer operator waits until an observer subscribes to it, and then it generates an Observable, typically with an Observable factory function.

代码看起来像这样:

Observable<MyObject> observable = Observable.defer(new Func0<Observable<MyObject>>() {
    @Override
    public Observable<MyObject> call() {

        System.out.println(Looper.myLooper() + " - " + Looper.getMainLooper());

        try {
            MyObject myObject = new MyObject();
            return Observable.just(myObject);
        }
        catch (Exception e) {
            return Observable.error(e);
        }

    }
});

Subscription s = observable
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
                new Action1<MyObject>() {
                    @Override
                    public void call(MyObject myObject) {

                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                }
        );

现在在您的 logcat 中您将获得:

I/System.out: null - Looper (main, tid 1) {5282c4e0}

Looper.myLooper() 函数 returns null 的原因是当你创建一个新线程时,除非你调用 Looper.prepare() 线程将没有循环程序。你通常不需要线程上的循环程序,除非你想 post 一个 Runnable 无论如何。