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

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

问题描述

我创建了带有无穷大进度条的简单活动,我正在尝试使用 RxJava 运行耗时的方法来防止 UI 线程阻塞,但每次 UI 线程都被阻塞.我认为我的解决方案在发出 Observable 方面存在问题.谁能帮我?我是 RX 的初学者.

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);

}

推荐答案

您的 doHeavyStuff() 在调用线程上执行计算,您只需将 result 包装到 Observable 中.为了将 computation 包装到 observable 中,您应该使用 defer

Your doHeavyStuff() executes computation on calling thread, you just wrap your 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());
    }
});

然后你可以通过 subscribeOnobserveOn 方法指定线程

then you can specify threads by subscribeOn and observeOn methods

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

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