RxAndroid

来源:互联网 发布:js给div设置内容 编辑:程序博客网 时间:2024/05/22 12:55

进程切换

RxAndroid 模块包含 RxJava 的 Android 特定的绑定代码。
它提供了一个可以在 UI 线程和任何给定的 Looper 上调度 Observable 的调度器 Scheduler。

Observable.just("one", "two", "three", "four", "five")    .subscribeOn(Schedulers.newThread())    .observeOn(AndroidSchedulers.mainThread())    .subscribe(/* an Observer */);

Observable 在一个新的线程执行,结果通过 onNext 在主线程发射。

Looper backgroundLooper = // ...Observable.just("one", "two", "three", "four", "five")        .observeOn(AndroidSchedulers.from(backgroundLooper))        .subscribe(/* an Observer */)

结果通过 onNext 在任何运行这个 Looper 的线程上发射。

Fragment和Activity生命周期

在 Android 上,要在异步操作中访问框架中的对象有些棘手,那是因为Andoid系统可以决定销毁(destroy)一个 Activity,当一个后台线程还在运行的时候,可能会引起两个问题:

  1. 造成内存泄漏。Activity 已经不可见了,但后台线程还持有它的引用。
  2. crash 崩溃。如果这个线程尝试访问已经死掉的 Activity 中的 View 对象。

所以在 Activity 中订阅一个 Observable 的结果时(无论是直接的还是通过一个内部类),必须在 onDestroy 里取消订阅,如:

private Subscription subscription;protected void onCreate(Bundle savedInstanceState) {    this.subscription = observable.subscribe(this);}...protected void onDestroy() {    this.subscription.unsubscribe();    super.onDestroy();}

这样确保所有指向订阅者(这个 Activity )的引用尽快释放,不会再有通知通过 onNext 发射给这个订阅者。

参考:
https://github.com/ReactiveX/RxAndroid
https://mcxiaoke.gitbooks.io/rxdocs/content/topics/The-RxJava-Android-Module.html

0 0
原创粉丝点击