RxSearchView Switch threads exception .Online waiting for - android

mSubscription = RxSearchView.queryTextChangeEvents(mSearchView)
.subscribeOn(AndroidSchedulers.mainThread())
.debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.filter(new Func1<SearchViewQueryTextEvent, Boolean>() {
#Override
public Boolean call(SearchViewQueryTextEvent searchViewQueryTextEvent) {
String query = searchViewQueryTextEvent.queryText().toString();
if (!TextUtils.isEmpty(query) && query.length() >= 11) {
if (!CommonUtil.isMobileNumber(query)) {
PromptManager.getInstance().showToast("please input valid phone");
return false;
}
}
boolean b = !TextUtils.isEmpty(searchViewQueryTextEvent.queryText().toString());
return b;
}
})
.switchMap(new Func1<SearchViewQueryTextEvent, Observable<BaseResponseWrapper<SearchUserResponse>>>() {
#Override
public Observable<BaseResponseWrapper<SearchUserResponse>> call(SearchViewQueryTextEvent searchViewQueryTextEvent) {
// Why run in the main thread here
// 2016/6/12 reset api request
String res = searchViewQueryTextEvent.queryText().toString();
return RetrofitManager.newInstance().getApi().searchUserByPhone(res);
}
})
// switch io thread
.subscribeOn(Schedulers.io())
.map(new Func1<BaseResponseWrapper<SearchUserResponse>, List<SearchUserResponse>>() {
#Override
public List<SearchUserResponse> call(BaseResponseWrapper<SearchUserResponse> fuzzyUserRes) {
// some code here
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<SearchUserResponse>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.w("end thread:" + Thread.currentThread().getName());
LogUtils.w("e :" + e);
**//there throw exception android.os.NetworkOnMainThreadException**
}
#Override
public void onNext(List<SearchUserResponse> fuzzyUsers) {
updateUI(fuzzyUsers);
}
});
When I input to the searchview , onError method will throw android.os.NetworkOnMainThreadException.
I have been in the
After switchmap switch to the IO thread.
I use rxjava version :
'io.reactivex:rxjava:1.1.5'.
what can I do?

You can't call subscribeOn twice in the same stream. Only the first will count.
Your code should look like this:
mSubscription = RxSearchView.queryTextChangeEvents(mSearchView)
.debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.filter(new Func1<SearchViewQueryTextEvent, Boolean>() {
#Override
public Boolean call(SearchViewQueryTextEvent searchViewQueryTextEvent) {
String query = searchViewQueryTextEvent.queryText().toString();
if (!TextUtils.isEmpty(query) && query.length() >= 11) {
if (!CommonUtil.isMobileNumber(query)) {
PromptManager.getInstance().showToast("please input valid phone");
return false;
}
}
boolean b = !TextUtils.isEmpty(searchViewQueryTextEvent.queryText().toString());
return b;
}
})
// switch io thread
.observeOn(Schedulers.io())
.switchMap(new Func1<SearchViewQueryTextEvent, Observable<BaseResponseWrapper<SearchUserResponse>>>() {
#Override
public Observable<BaseResponseWrapper<SearchUserResponse>> call(SearchViewQueryTextEvent searchViewQueryTextEvent) {
// Why run in the main thread here
// 2016/6/12 reset api request
String res = searchViewQueryTextEvent.queryText().toString();
return RetrofitManager.newInstance().getApi().searchUserByPhone(res);
}
})
.map(new Func1<BaseResponseWrapper<SearchUserResponse>, List<SearchUserResponse>>() {
#Override
public List<SearchUserResponse> call(BaseResponseWrapper<SearchUserResponse> fuzzyUserRes) {
// some code here
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<SearchUserResponse>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.w("end thread:" + Thread.currentThread().getName());
LogUtils.w("e :" + e);
**//there throw exception android.os.NetworkOnMainThreadException**
}
#Override
public void onNext(List<SearchUserResponse> fuzzyUsers) {
updateUI(fuzzyUsers);
}
});
As long as observeOn is a downstream operator, you should use them to switch over threads many times.
Hope that it helps.

Related

returning subscriber in RxJava after storing data fetch from webservice

I am trying to call the web service to fetch the data and storing it into database using following code. I have created a separate class to perform following operation.
Now , the issue is i want to notify my activity when i successfully fetch and store data in database. if some error occurs then i want to show that on UI itself.
somehow i am able to write a code to fetch the data using pagination but not sure how would i notify UI where i can subscribe catch the update related to progress and error if any.
public Flowable<Response> getFitnessData() {
Request request = new Request();
request.setAccess_token("d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0");
Flowable<Response> fitnessFlowable = new WebRequest()
.getRemoteClient()
.create(FitnessApi.class)
.getFitnessData("5b238abb4d3590001d9b94a8",request.toMap());
fitnessFlowable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.takeUntil(response->response.getSummary().getNext()!=null)
.subscribe(new Subscriber<Response>() {
#Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
#Override
public void onNext(Response response) {
Log.e(TAG, "onNext" );
if(response !=null){
if(response.getFitness()!=null && response.getFitness().size()!=0){
Realm realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(response.getFitness());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.i(TAG, "onSuccess , fitness data saved");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "onError , fitness data failed to save"+error.getMessage() );
}
});
}else{
Log.i(TAG, "onError , no fitness data available" );
}
}else{
Log.i(TAG, "onError , response is null" );
}
}
#Override
public void onError(Throwable t) {
Log.e(TAG, "onError" +t.getMessage());
}
#Override
public void onComplete() {
Log.e(TAG, "onComplete");
}
});;
return null;
}
Updated
Created RxBus to propagate events and error on UI
public class RxBus {
private static final RxBus INSTANCE = new RxBus();
private RxBus(){}
private PublishSubject<Object> bus = PublishSubject.create();
public static RxBus getInstance() {
return INSTANCE;
}
public void send(Object o) {
bus.onNext(o);
}
public void error(Throwable e){bus.onError(e);}
public Observable<Object> toObservable() {
return bus;
}
}
in activity
FitnessRepo fitnessRepo = new FitnessRepo();
fitnessRepo.getFitnessData();
RxBus.getInstance().toObservable().subscribe(new Observer<Object>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Object o) {
if(o instanceof RealmList ){
RealmList<Fitness> realmList = (RealmList<Fitness>) o;
Log.e(TAG,"Fitness data size "+realmList.size());
}
}
#Override
public void onError(Throwable e) {
Log.e(TAG,e.getMessage()+ "");
if (e instanceof HttpException) {
ResponseBody body = ((HttpException) e).response().errorBody();
try {
Response response= LoganSquare.parse(body.byteStream(),Response.class);
if(response.getErrors() !=null)
if(response.getErrors().size() > 0)
Log.e(TAG, "Error "+response.getErrors().get(0).getErrors());
} catch (IOException t) {
t.printStackTrace();
}
}
}
#Override
public void onComplete() {
}
});
in a web service call
public void getFitnessData() {
Request request = new Request();
request.setAccess_token("d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0");
request.setEnd_date("2018-07-01T00:00:00");
Flowable<Response> fitnessFlowable = new WebRequest()
.getRemoteClient()
.create(FitnessApi.class)
.getFitnessData("5b238abb4d3590001d9b94a8",request.toMap());
fitnessFlowable.subscribeOn(Schedulers.io())
.takeUntil(response->response.getSummary().getNext()!=null)
.doOnNext((response) -> {
if(response ==null || response.getFitness() == null || response.getFitness().isEmpty()) {
Log.e(TAG, " Error ");
return;
}
RxBus.getInstance().send(response.getFitness());
try(Realm r = Realm.getDefaultInstance()) {
r.executeTransaction((realm) -> {
realm.copyToRealmOrUpdate(response.getFitness());
});
}
}).subscribe(item ->{
},
error ->{
RxBus.getInstance().error(error);
});
}
I have good news for you! You can delete almost all of that code and just make it generally better as a result!
public void fetchFitnessData() {
Request request = new Request();
request.setAccess_token("d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0");
Flowable<Response> fitnessFlowable = new WebRequest()
.getRemoteClient()
.create(FitnessApi.class)
.getFitnessData("5b238abb4d3590001d9b94a8",request.toMap());
fitnessFlowable.subscribeOn(Schedulers.io())
.takeUntil(response->response.getSummary().getNext()!=null)
.doOnNext((response) -> {
if(response ==null || response.getFitness() == null || response.getFitness().isEmpty()) return;
try(Realm r = Realm.getDefaultInstance()) {
r.executeTransaction((realm) -> {
realm.insertOrUpdate(response.getFitness());
});
}
}
}).subscribe();
}
This method is on a background thread now and returns void, so the way to emit stuff out of this method would be to use either a PublishSubject (one for success, one for failure) or an EventBus.
private PublishSubject<Object> fitnessResults;
public Observable<Object> observeFitnessResults() {
return fitnessResults;
}
public static class Success {
public Success(List<Fitness> data) {
this.data = data;
}
public List<Fitness> data;
}
public static class Failure {
public Failure(Exception exception) {
this.exception = exception;
}
public Exception exception;
}
public void fetchFitnessData() {
...
fitnessResults.onNext(new Success(data));
} catch(Exception e) {
fitnessResults.onNext(new Failure(e));
And then
errors = observeFitnessResults().ofType(Error.class);
success = observeFitnessResults().ofType(Success.class);
There are different ways to achieve this. I will never handle the subscriptions on my own out of a lifecycle scope as it creates a possibility of memory leak. In your case it seems that both success and failure is bound to the UI so you can simply do this.
public Completable fetchFitnessData() {
Request request = new Request();
request.setAccess_token("d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0");
Flowable<Response> fitnessFlowable = new WebRequest()
.getRemoteClient()
.create(FitnessApi.class)
.getFitnessData("5b238abb4d3590001d9b94a8",request.toMap());
return fitnessFlowable.subscribeOn(Schedulers.io())
.takeUntil(response->response.getSummary().getNext()!=null)
.doOnNext((response) -> {
if(response ==null || response.getFitness() == null || response.getFitness().isEmpty()) return;
try(Realm r = Realm.getDefaultInstance()) {
r.executeTransaction((realm) -> {
realm.insertOrUpdate(response.getFitness());
});
}
}
}).ignoreElements();
}
At UI level, you can just handle your subscription with both success and failure. In case you need success model can replace Completable with Single or Flowable.
fetchFitnessData.subscrible(Functions.EMPTY_ACTION, Timber::d);
The major advantage with this approach is that you handle your subscription lifecycles.

rxjava run multiple observable sequence with condition

i have 4 observable, and i want call it sequence
Observable1 //return boolean
-> Observable2 // if(Observable1 result == true) { call Observable3 } else { call observable4 }
-> Observable3 // call Observable4
-> Observable4
-> subscribe();
i tried it, but when Observable1 result is false onCompleted called
Observable
.fromCallable(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
return false;
}
})
.flatMap(new Func1<Boolean, Observable<String>>() {
#Override
public Observable<String> call(Boolean aBoolean) {
if(aBoolean) {
return Observable.just("to Observable2");
}
return null; // to Observable 3
}
})
.flatMap(new Func1<String, Observable<Integer>>() {
#Override
public Observable<Integer> call(String s) {
return Observable.just(1); //to Observable3
}
})
.flatMap(new Func1<Integer, Observable<Boolean>>() {
#Override
public Observable<Boolean> call(Integer integer) {
return Observable.just(true); //success
}
})
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
Log.e("TAG", "onCompleted");
}
#Override
public void onError(Throwable e) {
Log.e("TAG", "onError", e);
}
#Override
public void onNext(Boolean bool) {
Log.e("TAG", "onNext");
}
});
how can achieve to this ?
thanks
There are many ways of doing this. Only proposed this based on the first pseudocode you are offering.
Observable.just(boolean)
.flatmap( boolean -> if (boolean) return Observable3
else return Observable.just(boolean))
.flatmap(boolean -> Observable4)
.subscribe()
i solved this problem with define observables as functions
public void run() {
Observable
.fromCallable(() -> false)
.flatMap(bool -> {
if(bool) {
return getObservable2();
}
return getObservable3();
})
.subscribe(bool -> {
Log.e("TAG", "onNext");
}, e -> {
Log.e("TAG", "onError", e);
}, () -> {
Log.e("TAG", "onCompleted");
});
}
private Observable<Boolean> getObservable2() {
return Observable
.just("test")
.flatMap(s -> getObservable4());
}
private Observable<Boolean> getObservable3() {
return Observable
.just(1)
.flatMap(s -> getObservable4());
}
private Observable<Boolean> getObservable4() {
return Observable.just(true);
}
Observable.just(boolean)
.flatmap( boolean -> if (boolean)
return Observable3.flatmap(observable4)
else return Observable4))
.subscribe()
if the result of first observable is true than obervablr3 is called whose result is then flat mapped into the observable4 second case is if the result of first observable is false then it will call observable4 directly and the result is subscribes in first observable only
This is how I would attempt to solve your problem but it doesn't use flatmap.
Observable2.subscribe( aBoolean -> if(aBoolean){
Observable3.subscribe();
} else {
Observable2.subscribe( result -> Observable3.subscribe());
}
You should never return null from an Observable

How do I throw an exception in an Observable?

I'm trying to validate data so that I can throw an exception that will be specifically handled by the subscriber's onError, but I can't figure out how to throw the exception. This is current attempt:
Realm.getDefaultInstance()
.asObservable()
.map(new Func1<Realm, RealmResults<NewsFeed>>() {
#Override
public RealmResults<NewsFeed> call(Realm realm) {
return realm.where(NewsFeed.class).findAll();
}
})
.flatMap(new Func1<RealmResults<NewsFeed>, Observable<?>>() {
#Override
public Observable<?> call(RealmResults<NewsFeed> newsFeed) {
if(newsFeed.size() == 0) {
// can't do this
return Observable.error(new NoDataException());
}
return newsFeed.first().asObservable();
}
});
This doesn't work because as far as I know, the observable stream must be homogeneous.
Observable on the flatMap func1 should be Observable.
Realm.getDefaultInstance()
.asObservable()
.map(new Func1<Realm, RealmResults<NewsFeed>>() {
#Override
public RealmResults<NewsFeed> call(Realm realm) {
return realm.where(NewsFeed.class).findAll();
}
})
.flatMap(new Func1<RealmResults<NewsFeed>, Observable<NewsFeed>>() {
#Override
public Observable<NewsFeed> call(RealmResults<NewsFeed> newsFeed) {
if(newsFeed.size() == 0) {
return Observable.error(new NoDataException());
}
return newsFeed.first().asObservable();
}
})
You just need to use the plain old Java throw statement there. Exceptions that are not handled within stream operators will be forwarded to the onError block of your subscriber.
Realm.getDefaultInstance()
.asObservable()
.map(new Func1<Realm, RealmResults<NewsFeed>>() {
#Override
public RealmResults<NewsFeed> call(Realm realm) {
return realm.where(NewsFeed.class).findAll();
}
})
.flatMap(new Func1<RealmResults<NewsFeed>, Observable<?>>() {
#Override
public Observable<?> call(RealmResults<NewsFeed> newsFeed) {
if(newsFeed.size() == 0) {
throw new NoDataException();
}
return newsFeed.first().asObservable();
}
});

Retrofit Periodic call with Pagination

I am currently using the Retrofit2.0 to poll the server .I am getting the result in x second but the problem is page number is not updating in the API.Lets come to the code for better clarification
private void startPolling() throws Exception {
Log.e("APP CONSTANT","" + current_page);
MrSaferWebService service = ServiceFactory.createRetrofitService(MrSaferWebService.class, AppConstants.BASE_URL);
final Observable<ReportResponse> reportResponseObservable = service.getListOfInciden("get_report", current_page, 5, incident_lat, incident_long);
Observable.interval(0,20,TimeUnit.SECONDS)
.flatMap(new Func1<Long, Observable<ReportResponse>> () {
#Override
public Observable<ReportResponse> call(Long aLong) {
return reportResponseObservable;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ReportResponse>() {
#Override
public void call(ReportResponse response) {
Log.i("HEARTBEAT_INTERVAL", "Response from HEARTBEAT");
ActivityUtils.showProgress(false, mRootView, mProgressView, mContext);
if (response.getStatus() == 1) {
current_page = current_page + 1;
if (!response.getReportList().isEmpty()) {
addItems(response.getReportList());
}
else{
//do nothing
}
} else {
Log.e("MY ERROR", "" + "SOME ERROR OCCURED");
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
ActivityUtils.showProgress(true, mRootView, mProgressView, mContext);
// TODO: 22/03/16 ADD ERROR HANDLING
}
});
}
As you can see i have incremented the current_page by 1 every time on
SuccessFull Response but when i check the Log the current_page value are increased only once and after that log are not there and hence there value is also not increasing..So it taking the the same page number every time and giving me the Duplicate response.
Please help me to find what i am missing.
After spending more than a day i just changed Action with Subscriber and everything seems to be working .I don't know what happen internally but it works . I am still trying to figure it out what the difference between Action and Subscriber.
Below are my updated code which did the tricks.
private void startPolling() throws Exception {
final MrSaferWebService service = ServiceFactory.createRetrofitService(MrSaferWebService.class, AppConstants.BASE_URL);
Observable
.interval(0,20,TimeUnit.SECONDS)
.flatMap(new Func1<Long, Observable<ReportResponse>>() {
#Override
public Observable<ReportResponse> call(Long aLong) {
Log.e("PAGE", "" + current_page);
return service.getListOfInciden("get_report", current_page, 5, incident_lat, incident_long);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ReportResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
if (mProgressView !=null && mRootView !=null) {
ActivityUtils.showProgress(false, mRootView, mProgressView, mContext);
}
}
#Override
public void onNext(ReportResponse response) {
if (mProgressView !=null && mRootView !=null) {
ActivityUtils.showProgress(false, mRootView, mProgressView, mContext);
}
if (response.getStatus() == 1) {
if (!response.getReportList().isEmpty()){
current_page = current_page + 1;
addItems(response.getReportList());
}
else{
//do nothing
}
} else {
Log.e("MY ERROR", "" + "SOME ERROR OCCURED");
}
}
});
}

how to change Schedulers in RxAndroid?

I want to use RxAndroid in my project,
and i make the thread sleep for 50ms
but it caused anr,the code
public void getTypeAndCommodity() {
Observable.from(getCommodities())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Commodity>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(Commodity commodity) {
}
});
}
and the getCommodities:
private ArrayList<Commodity> getCommodities() {
// some test info
ArrayList<Commodity> list = new ArrayList<>();
for (int i = 0; i < 99; i++) {
Commodity commodity = new Commodity();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
commodity.setName("name" + i);
commodity.setType("type" + (i + 1) / 10);
list.add(commodity);
}
return list;
}
why it cause anr?please help
This happens because getCommodities() is executed in main thread, and only the item emited is executed in io thread with subscribeOn(Schedulers.io()). If you want to execute getCommidities() in background thread too, you need to create an observable with defer() method:
Observable.defer(new Func0<Observable<Object>>() {
#Override public Observable<Object> call() {
return Observable.from(getCommodities());
}
}).subscribeOn(Schedulers.io())...
If you need more info: http://blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/

Categories

Resources