2015-11-02

[Android][RxJava] Run something async on non-UI thread, then back to MainThread to do something after that.


當你有某些東西要Async地在background、而且是non-UI thread運作
(例如:Android要連接網路Network、http之類的時候)

但是做完又要回到Main Thread
(例如:從網路or anywhere拿到資料之後要更新UI)

就可以用以下的Pattern來寫


Async.fromCallable(new Callable() {
    // T is the type you want to send back to MainThread
    @Override public T call() throws Exception {
        // do something that you want it async run on Schedulers.io()
        return [object in type T];
    }
}, Schedulers.io())  
// specify the thread you want async work to run on it, here we use Schedulers.io()

    .observeOn(AndroidSchedulers.mainThread())  // then back to MainThread
    .subscribe(new Subscriber() {
        // run on MainThread
        @Override public void onCompleted() {

        }

        @Override public void onError(Throwable e) {

        }

        @Override public void onNext(T obj) {

        }
    });