I have tried to create the async task using the RxJAVA2. The code is working fine. WHat enhancement can I do in this code?
private void createObservable(){
progressDialog =new ProgressDialog(ProductActivityRx.this);
progressDialog.setTitle("Data fetching...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
Observable<List<Product>> booksObservable =Observable.fromCallable(new Callable<List<Product>>() {
@Override
public List<Product> call() throws Exception {
return getProductList();
}
}).doOnNext(new Consumer<List<Product>>() {
@Override
public void accept(List<Product> strings) throws Exception {
}
});
productSubscription = booksObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Consumer<List<Product>>() {
@Override
public void accept(List<Product> productList) throws Exception {
displayData(productList);
}
});
}
I am updating the UI in displayData().
1 Answer 1
in general, I believe it would be better if you included this in some sort of chain. What I mean here:
- don't return void, rather an
Observable
- don't show the progress dialog in the function, rather delegate it to the part responsible for UI. Same with
displayData()
- where's the whole function called? What calls it? Where is it located, in an Activity?
- don't return void, rather an
doOnNext()
can be gotten rid of - there's no action in hereAre you getting just one result at a time? I mean, is the function called perpetually on and on and on, and you just evaluate the result each time? Perhaps you could use
Single
orMaybe
, which is better suited for single results.
Good luck and hope we'll both learn something along the way.