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);
}
Using handlers To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.
thread. run() is going to execute the code in the thread's run method on the current thread. You want thread. start() to run thread in background.
Main thread. Android modifies the user interface and handles input events from one single thread, called the main thread. Android collects all events in this thread in a queue and processes this queue with an instance of the Looper class.
With RxJava2 a possible solution is:
Single.fromCallable(() -> loadInBackground())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((resultObject) -> { updateUi(resultObject) });
Single.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return loadInBackground();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object resultObject) throws Exception {
updateUi(resultObject);
}
});
private Object loadInBackground() {
// some heavy load code
return resultObject;
}
private void updateUi(Object resultObject) {
// update your Views here
}
According to docs
Deprecated: fromFunc0 Unnecessary now that Func0 extends Callable. Just call fromCallable(java.util.concurrent.Callable) instead.
So you could make the call in this way:
Observable.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return someMethod();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
@Override
public void call(Object object) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With