As shown in the following code, I would like to use RxAndroid. but when i run the code, i dont receive any logs from
#Override
public void onNext(String s) {
Log.d(TAG, "Name: " + s);
}
please let me know hopw to fix these issue.
code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Observer<String> animalsObserver = getAnimalsObserver();
getAnimalsObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.filter(new Func1<String, Boolean>() {
#Override
public Boolean call(String s) {
return s.toUpperCase().equals("D");
}
})
.subscribe(animalsObserver);
}
private Observable getAnimalsObservable() {
return Observable.from(Arrays.asList(
new String[] {
"Ant", "Ape",
"Bat", "Bee", "Bear", "Butterfly",
"Cat", "Crab", "Cod",
"Dog", "Dove",
"Fox", "Frog"
}
));
}
private Observer<String> getAnimalsObserver() {
return new Observer<String>() {
#Override
public void onNext(String s) {
Log.d(TAG, "Name: " + s);
}
#Override
public void onError(Throwable e) {
Log.e(TAG, "onError: " + e.getMessage());
}
#Override
public void onCompleted() {
Log.d(TAG, "All items are emitted!");
}
};
}
}
return s.toUpperCase().equals("D");
this is always false. You might want to check with startsWith. You can read more here
Related
Activity
#Override
protected void onResume() {
super.onResume();
getCartList();
}
private void getCartList() {
showProgressDialog();
Call<List<CartList>> call = api.getCartList(1);
call.enqueue(new Callback<List<CartList>>() {
#Override
public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
cartLists = response.body();
if (cartLists.size() == 0) {
tvCartEmpty.setVisibility(View.VISIBLE);
progressDialog.cancel();
} else {
addToCartAdapter.setData(cartLists);
productList.setAdapter(addToCartAdapter);
progressDialog.cancel();
}
}
#Override
public void onFailure(Call<List<CartList>> call, Throwable t) {
Toast.makeText(AddToCartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void deleteItemID(int id) {
Call<CartList> deleteCall = api.deleteCartItem(id);
deleteCall.enqueue(new Callback<CartList>() {
#Override
public void onResponse(Call<CartList> call, Response<CartList> response) {
Log.d(TAG, "deleteItem by id" + response.code());
onResume();
}
#Override
public void onFailure(Call<CartList> call, Throwable t) {
Log.d(TAG, t.getMessage());
}
});
}
i mean last is deleting but not updating on the spot even though i called onresume in delete item method.
i have to open that activity again to see updted result
i hope i will get my query solved soon!
thanks
if you want i will upload inteface and adapter code. which i do not think necessary here.
Solution
just had to add this in response class
public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
cartLists = response.body();
if (cartLists.size() == 0) {
tvCartEmpty.setVisibility(View.VISIBLE);
tvCartItems.setText("0 items");
addToCartAdapter.setData(cartLists);
progressDialog.cancel();
} else {
addToCartAdapter.setData(cartLists);
productList.setAdapter(addToCartAdapter);
tvCartItems.setText(cartLists.size() + " Items");
progressDialog.cancel();
}
}
you don't need to call onResume() again.
instead of that you should use the following snippet:
cartLists.removeAt(id);
addToCartAdapter.notifyDataSetChanged();
your deleteItem function would look like below code:
#Override
public void deleteItemID(int id) {
Call<CartList> deleteCall = api.deleteCartItem(id);
deleteCall.enqueue(new Callback<CartList>() {
#Override
public void onResponse(Call<CartList> call, Response<CartList> response) {
Log.d(TAG, "deleteItem by id" + response.code());
cartLists.removeAt(id);
addToCartAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<CartList> call, Throwable t) {
Log.d(TAG, t.getMessage());
}
});
Before I always used retrofit to load data. It's very easy to handle or get status code of the response.
But now I want to use Retrofit with RxJava but I don't know how to handle or get the https status code of the response in onNext method.
progressDialog.show();
Observable<ResponseData> observable = apiService.getData();
compositeDisposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<ResponseData>() {
#Override
public void onNext(ResponseData responseData) {
Log.e("pppp", "onNext: " + responseData.toString());
}
#Override
public void onError(Throwable e) {
progressDialog.dismiss();
Log.e("pppp", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
progressDialog.dismiss();
Log.e("pppp", "onComplete");
}
})
);
Everyone, please help me to solve this problem.
Thanks!
You should wrap your ResponseData inside Response as
Observable<Response<ResponseData>> observable = apiService.getData();
Then inside onNext
#Override
public void onNext(Resposne<ResponseData> response) {
int statusCode = response.code();
}
and for error
#Override
public void onError(Throwable e) {
((HttpException) e).code();
}
responseData.code gives you the status code
int statusCode = responseData.code();
for getting status
Observable<ResponseData> observable = apiService.getData();
compositeDisposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<ResponseData>() {
#Override
public void onNext(ResponseData responseData) {
int statusCode = responseData.code();
// here you get your status code
Log.e("statusCode ", "onNext: " + statusCode );
}
#Override
public void onError(Throwable e) {
progressDialog.dismiss();
Log.e("pppp", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
progressDialog.dismiss();
Log.e("pppp", "onComplete");
}
})
);
I am trying to make webservie call using retrofit and rxjava 2. i was exploring two different approach to use RxJava2. problem is i am getting response whene i use Observable but it is not working with Flowable. Logs are not getting printed when using Flowable i tried to debug it but its not going inside onNext or onComplete or onError. only onSubscribe gets executed.
1) using observable as return type
new WebRequestManager().getContactObservable(userRequest)
.subscribe(new Observer<ResponseData>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(ResponseData responseData) {
Log.e(TAG , "data "+responseData.getStatus());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
Log.e(TAG , "data complete");
}
}
);
2) Using flowable as return type
new WebRequestManager().getContactFlowable(userRequest)
.subscribe(new Subscriber<ResponseData>() {
#Override
public void onSubscribe(Subscription s) {
Log.e(TAG , "contact subscription ");
}
#Override
public void onNext(ResponseData responses) {
Log.e(TAG , "contact onNext ");
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
Log.e(TAG , "contact onComplete ");
}
});
Rest contact retrofit api
public interface ContactApi {
#POST(WebRequest.GET_CONTACTS)
Flowable<ResponseData> getContactFlowable(#Body UserRequest userRequest);
#POST(WebRequest.GET_CONTACTS)
Observable<ResponseData> getContactObservable(#Body UserRequest userRequest);
}
call to webservice
public Flowable<ResponseData> getContactsData(UserRequest userRequest){
return webRequest.getWebClient().create(ContactApi.class).getContacts(userRequest);
}
public Observable<ResponseData> getContact(UserRequest userRequest){
return webRequest.getWebClient().create(ContactApi.class).getContact(userRequest);
}
getting retrofit instance
public static Retrofit getWebClient(){
//if(okHttpClient == null)
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(120,TimeUnit.SECONDS)
.readTimeout(120,TimeUnit.SECONDS)
.writeTimeout(120,TimeUnit.SECONDS)
.addInterceptor(new WebRequestInterceptor("\"application/json\""))
.build();
// if(client == null)
client = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(LoganSquareConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return client;
}
With Subscribers, you have to call request to get items:
new WebRequestManager().getContactFlowable(userRequest)
.subscribe(new Subscriber<ResponseData>() {
#Override
public void onSubscribe(Subscription s) {
Log.e(TAG , "contact subscription ");
s.request(Long.MAX_VALUE); // <---------------------------------
}
#Override
public void onNext(ResponseData responses) {
Log.e(TAG , "contact onNext ");
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
Log.e(TAG , "contact onComplete ");
}
});
See also DisposableSubscriber with its example.
Android how to check the unit test with powermockito
public void updateProfile(final UserLogin updateUser) {
profileModelImple.updateUser(updateUser)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
#Override
public void onCompleted () {
}
#Override
public void onError (Throwable e) {
Timber.e("authenticationModel -> login " + e);
EventBus.getDefault().post(null);
}
#Override
public void onNext (Object user) {
}
});
}
I'm new to rxjava 2 and i'm trying to execute someMethod in the background with a given interval and use the result on the UI thread. Can someone point me where i made mistake in my code or even better provide optimal code that does the job i need?
#Override
protected void onStop() {
subject.onNext(Long.valueOf(10005));
observable.unsubscribeOn(Schedulers.io());
super.onStop();
}
private void initAzimuthUpdater() {
subject = PublishSubject.create();
observable = Observable.interval(500, TimeUnit.MILLISECONDS)
.takeWhile(new Predicate<Long>() {
#Override
public boolean test(#NonNull Long aLong) throws Exception {
Log.d(TAG, "xxxxxxxxxxxx test: " + aLong);
return aLong != Long.valueOf(10005);
}
});
observable.flatMap(new Function<Long, ObservableSource<Float>>() {
#Override
public ObservableSource<Float> apply(#NonNull Long aLong) throws Exception {
return PublishSubject.create(new ObservableOnSubscribe<Float>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Float> e) throws Exception {
e.onNext(someMethod());
}
});
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Float>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
Log.d(TAG, "xxxxxxxx onSubscribe:" + System.currentTimeMillis());
isRunning = true;
}
#Override
public void onNext(#NonNull Float o) {
Log.d(TAG, "xxxxxxxx onNext:" + System.currentTimeMillis());
//update UI
}
#Override
public void onError(#NonNull Throwable e) {
Log.d(TAG, "xxxxxxxx onError:" + System.currentTimeMillis());
}
#Override
public void onComplete() {
Log.d(TAG, "xxxxxxxx onComplete:" + System.currentTimeMillis());
}
});
subject.mergeWith(azimuthObservable);
}
You should use DisposableObserver and subscribeWith, save the Disposable into a CompositeDisposable, then call clear() on it from onStop(). The Observable operators return a new instance so ignoring their return value will have no effect on the original flow.
CompositeDisposable composite = new CompositeDisposable();
#Override
protected void onStop() {
composite.clear();
super.onStop();
}
private void initAzimuthUpdater() {
Disposable d = Observable.interval(500, TimeUnit.MILLISECONDS)
.flatMap(new Function<Long, ObservableSource<Float>>() {
#Override
public ObservableSource<Float> apply(#NonNull Long aLong)
throws Exception {
return Observable.create(new ObservableOnSubscribe<Float>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Float> e)
throws Exception {
e.onNext(someMethod());
}
});
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<Float>() {
#Override
public void onStart() {
Log.d(TAG, "xxxxxxxx onSubscribe:" + System.currentTimeMillis());
isRunning = true;
}
#Override
public void onNext(#NonNull Float o) {
Log.d(TAG, "xxxxxxxx onNext:" + System.currentTimeMillis());
//update UI
}
#Override
public void onError(#NonNull Throwable e) {
Log.d(TAG, "xxxxxxxx onError:" + System.currentTimeMillis());
}
#Override
public void onComplete() {
Log.d(TAG, "xxxxxxxx onComplete:" + System.currentTimeMillis());
}
});
composite.add(d);
}