Issue
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);
}
Solution
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());
}
});
then you can specify threads by subscribeOn and observeOn methods
Answered By - krp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.