.timeout with RxJava observer - java

I have a subscriber that times out in 10 seconds. Where do I pass what happens once the timeout has occurred?
Service.registerUser(registerUserRequest)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.timeout(10, TimeUnit.SECONDS)
.subscribe(new SingleObserver<RegisterUserResponse>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(RegisterUserResponse registerUserResponse) {
}
}
#Override
public void onError(Throwable e) {
Log.e(LogTags.API, "Error occurred while registering new user.");
e.printStackTrace();
}
});

If timeout occurs the onError would be invko TimeoutException so you can check that in onError method with this if:
if( e instanceof TimeoutException)
check this link out : http://reactivex.io/documentation/operators/timeout.html

Related

Without Completable.defer I don't know where my function works

I'm confused. I not found any articles about that.
Check my example, in this case longOperation will work on Schedulers.io()
private Completable longOperation() throws InterruptedException {
Thread.sleep(5000);
return Completable.complete();
}
private void doSomething() throws InterruptedException {
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(Completable.defer(() -> longOperation())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableCompletableObserver() {
#Override
public void onComplete() {
customToast("long operation done");
}
#Override
public void onError(Throwable e) {
}
}));
}
but if I will remove Completable.defer(() -> longOperation()
private void doSomething() throws InterruptedException {
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(longOperation()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableCompletableObserver() {
#Override
public void onComplete() {
customToast("long operation done");
}
#Override
public void onError(Throwable e) {
}
}));
}
I don't know where.
On which thread my method 'longOperation' will work ? I ask because my UI is freezed after invoke doSomething without Completable.defer.

How to get play and stop event callback from chromecast android

I want to get callback event and perform some function when chromecast audio change there playback mode(play/stop)
How can I get the play/stop event to the application so I will do my work on that event.
Please check below logic I have implemented.
private void setupCastListener() {
mSessionManagerListener = new SessionManagerListener<CastSession>() {
#Override
public void onSessionEnded(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionResumed(CastSession session, boolean wasSuspended) {
onApplicationConnected(session);
}
#Override
public void onSessionResumeFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarted(CastSession session, String sessionId) {
onApplicationConnected(session);
}
#Override
public void onSessionStartFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarting(CastSession session) {
}
#Override
public void onSessionEnding(CastSession session) {
}
#Override
public void onSessionResuming(CastSession session, String sessionId) {
if(mCastSession!=null && isChromeCastConnected){
try {
if (session.isMute()) {
mStopPlayButton.setImageResource(R.drawable.ic_play);
isChromeCastPlay = false;
//mCastSession.setMute(!mCastSession.isMute());
} else {
mStopPlayButton.setImageResource(R.drawable.ic_stop);
isChromeCastPlay = true;
//mCastSession.setMute(!mCastSession.isMute());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onSessionSuspended(CastSession session, int reason) {
}
};
}
Please let me know. thanks
You need to read this documentation, and focus on RemoteMediaClient and the Listener interface there. The callback onStatusUpdated() will be called when there is a change in the playback status. Tutorials available on the first link above is very informative, so make sure you read about things there.
Finally I found the remote media play and pause mode call back by below MediaControlIntent.
Remote Playback Routes
mMediaRouter = MediaRouter.getInstance(this);
mSelector = new MediaRouteSelector.Builder()
.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
.build();

Rx Java zip completes when any subject completes

I am facing with the problem. As far as I know zip method from RxJava waits for all observables to complete.
But am I getting another behaviour.
Here is my code snippet
private PublishSubject<Void> firstSubject;
private PublishSubject<Void> secondSubject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
mDrawerHeaderView.postDelayed(new Runnable() {
#Override
public void run() {
// getSecondSubject().onNext(null);
}
}, 1000);
mDrawerHeaderView.postDelayed(new Runnable() {
#Override
public void run() {
getFirstSubject().onCompleted();
}
}, 1000);
}
protected PublishSubject<Void> createFirstSubject() {
firstSubject = PublishSubject.create();
return firstSubject;
}
protected PublishSubject<Void> createSecondSubject() {
secondSubject = PublishSubject.create();
return secondSubject;
}
protected PublishSubject<Void> getFirstSubject() {
return firstSubject;
}
protected PublishSubject<Void> getSecondSubject() {
return secondSubject;
}
private void loadData() {
Observable<Void> firstSubject = createFirstSubject();
Observable<Void> secondSubject = createSecondSubject();
Observable<Boolean> allDataTask = Observable.zip(firstSubject, secondSubject, new Func2<Void, Void, Boolean>() {
#Override
public Boolean call(Void aVoid, Void aVoid2) {
return true;
}
});
allDataTask
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
Notifications.showSuccessMessage(getApplicationContext(), "COMPLETE");
}
#Override
public void onError(Throwable e) {
Notifications.showErrorMessage(getApplicationContext(), "ERROR");
}
#Override
public void onNext(Boolean aBoolean) {
Notifications.showSuccessMessage(getApplicationContext(), "NEXT");
}
});
}
In this case I got COMPLETE message, but I was expecting to get nothing because the second subject is not completed.
What I am doing wrong ?
Please help me to get desired behaviour.
Yes, it works as expected. It makes perfect sense to receive the onCompleted() here, because if one stream is done, as long as all the elements it emitted are "zipped", there's no way to "zip" anything more, so it's "completed". You can also play with the sequence here.

How To Use Threading on RxJava?

Observable.create(new Observable.OnSubscribe<Integer>() {
public void call(final Subscriber<? super Integer> obs) {
new Thread(){
public void run(){
obs.onNext(1);
}
}.start();
new Thread(){
public void run(){
obs.onNext(2);
}
}.start();
new Thread(){
public void run(){
obs.onNext(3);
}
}.start();
obs.onCompleted();
}
}).subscribe(new Subscriber<Integer>(){
public void onCompleted() {
System.out.println("Complete");
}
public void onError(Throwable arg0) {
// TODO Auto-generated method stub
}
public void onNext(Integer arg0) {
System.out.println(arg0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
As you see , I want to do multi-threading on Java with RxJava
I've studied many resources on Google , but most of them are for Android
Can anybody tell what is the easiest way to implement it ?
I think my code is a little :<
Well, it's a bit unclear what you're asking, but it is worthwhile to at least have a cursory read over the Observable class, as it has a lot of methods that will make your life easier. For example, your code roughly translates to:
Observable
.just(1,2,3)
.subscribeOn(Schedulers.io())
.zipWith(Observable.interval(1000,1000,TimeUnit.milliseconds),
(item, pos) -> item)
.doOnCompleted(() -> System.out.println("Complete");
.subscribe(item -> System.out.println(item));
However, you first need to be clear on what do you want to do - can you put it to words?

Android Volley RxJava - Multiple Requests

I have something like that:
public void function sendPhotosAndSave (ArrayList<Photo> photos) {
// Iterate through all photos
// Send a POST request using volley for each photo
// Alert when all photos sended
// ????
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
// Save
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(Boolean aBoolean) {
}
});
}
I need to send all photos (Multipart/POST) and then send a save request.
How do i iterate the photos requests using RxJava and known when it's done?
You can do something like this:
public void sendPhotosAndSave(List<Photo> photos) {
Observable.from(photos)
.flatMap(photo -> sendRequest(photo).subscribeOn(Schedulers.io()))
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
// Save
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(Boolean aBoolean) {
}
});
}
private Observable<Boolean> sendRequest(Photo photo) {
return Observable.just(/*your request logic*/);
}

Categories