简体   繁体   English

如何在RxAndroid中更改调度程序?

[英]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 我想在我的项目中使用RxAndroid,我使线程休眠50毫秒,但它导致了错误,代码

    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: 和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()). 发生这种情况是因为getCommodities()在主线程中执行,并且只有发出的项目才在io线程中使用subscriptionOn(Schedulers.io())执行。 If you want to execute getCommidities() in background thread too, you need to create an observable with defer() method: 如果您也想在后台线程中执行getCommidities(),则需要使用defer()方法创建一个可观察对象:

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/ 如果您需要更多信息,请访问: http : //blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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