2016-05-14 55 views
0

我正在使用RxAndroid在后台做一些东西。这是我的代码: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()为您提供了线程的名称标识当前的代码运行并Looper.getMainLooper()给你的ID的主线程。当我运行应用程序时,在SysOut中,它会为它们打印出相同的ID。

我做错了什么或者我误解了2 Looper功能?

回答

2

建议您不要使用Observable.create,除非您真的知道您在使用Observable做什么。有很多东西可能会导致错误。

原因里面你制作的是这里的主线程上运行的代码是可观察到的正在创建时,当你订阅它,它被调用。

对于你正在努力实现我会用Observable.deferdocs

将推迟运营商将等待观察订阅它,然后它会产生可观察到的,通常可观察到的工厂函数。

的代码看起来是这样的:

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()函数返回空值的原因是,当你创建一个新的线程除非你打电话Looper.prepare()线程不会有活套。除非你想发布Runnable,否则你通常不需要在线程中使用活套。

+0

嘿。抱歉。已经离开了一段时间。我今晚会尝试一下,回到你身边:) –