AndroidRX - 在后台运行的方法 [英] AndroidRX - run method in background

查看:189
本文介绍了AndroidRX - 在后台运行的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了无限进步党条简单的活动,和我'尝试运行时使用RxJava至prevent UI线程阻塞消耗的方法,但每次UI线程被阻塞。我想,我的解决方案具有发射观测问题。谁能帮我?我'初学者在RX。

 公共类MainActivity扩展AppCompatActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
}公共无效DoSomething的(查看视图){
    doHeavyStuff()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(新措施1(){
                @覆盖
                公共无效调用(对象o){
                    Toast.makeText(getApplicationContext(),结束,Toast.LENGTH_SHORT).show();
                }
            })
            。订阅();
}私人观测doHeavyStuff(){
    的for(int i = 0; I< 999999999;我++){
        为(中间体J = 0; J&2; J ++){
        }
    }
    返回Observable.just(1);}


解决方案

您doHeavyStuff()调用上的线程执行计算,你只需换您导致进入观察到。
为了计算包成可观察的,你应该使用的延迟

  Observable.defer(新Func0<&可观察到的LT;整数GT;>(){
    @覆盖
    公众可观察<整数GT;调用(){
        返回Observable.just(doHeavyStuff());
    }
});

然后就可以通过指定的 subscribeOn 的线程和的 observeOn 的方法

I created simple activity with infinity progres bar, and I'am trying to run time consuming method using RxJava to prevent UI thread from blocking, but everytime UI thread is blocked. I think my solution has problem with emitting Observable. Can anyone help me? I'am begginer in RX.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void doSomething(View view) {
    doHeavyStuff()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(new Action1() {
                @Override
                public void call(Object o) {
                    Toast.makeText(getApplicationContext(), "FINISHED", Toast.LENGTH_SHORT).show();
                }
            })
            .subscribe();
}

private Observable doHeavyStuff() {
    for (int i = 0; i < 999999999; i++) {
        for (int j = 0; j < 2; j++) {
        }
    }
    return Observable.just(1);

}

解决方案

Your doHeavyStuff() executes computation on calling thread, you just wrap you result into Observable. In order to wrap computation into observable you should use defer

Observable.defer(new Func0<Observable<Integer>>() {
    @Override
    public Observable<Integer> call() {
        return Observable.just(doHeavyStuff());
    }
});

then you can specify threads by subscribeOn and observeOn methods

这篇关于AndroidRX - 在后台运行的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆