简体   繁体   中英

how to change Schedulers in RxAndroid?

I want to use RxAndroid in my project, and i make the thread sleep for 50ms but it caused anr,the code

    public void getTypeAndCommodity() {
    Observable.from(getCommodities())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Commodity>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Commodity commodity) {
                }
            });
}

and the getCommodities:

    private ArrayList<Commodity> getCommodities() {
    // some test info
    ArrayList<Commodity> list = new ArrayList<>();
    for (int i = 0; i < 99; i++) {
        Commodity commodity = new Commodity();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        commodity.setName("name" + i);
        commodity.setType("type" + (i + 1) / 10);
        list.add(commodity);
    }
    return list;
}

why it cause anr?please help

This happens because getCommodities() is executed in main thread, and only the item emited is executed in io thread with subscribeOn(Schedulers.io()). If you want to execute getCommidities() in background thread too, you need to create an observable with defer() method:

Observable.defer(new Func0<Observable<Object>>() {
        @Override public Observable<Object> call() {
            return Observable.from(getCommodities());
        }
    }).subscribeOn(Schedulers.io())...

If you need more info: http://blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM