com.stanfy.enroscar.async.internal.ObservableAsyncProvider Maven / Gradle / Ivy
package com.stanfy.enroscar.async.internal;
import com.stanfy.enroscar.async.Async;
import com.stanfy.enroscar.async.AsyncObserver;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;
/**
* Adapts {@link rx.Observable} to {@link com.stanfy.enroscar.async.Async}.
* @param data type
* @author Roman Mazur - Stanfy (http://stanfy.com)
*/
public abstract class ObservableAsyncProvider implements AsyncProvider {
@Override
public final Async provideAsync() {
return new RxAsync<>(provideObservable());
}
protected abstract Observable provideObservable();
/**
* Adapter.
* @param data type
*/
private static class RxAsync implements Async {
/** Observable. */
private final Observable rxObservable;
/** Cancellation flag. */
private boolean canceled;
/** Current subscription. */
private Subscription subscription;
private RxAsync(Observable rxObservable) {
this.rxObservable = rxObservable;
}
@Override
public RxAsync replicate() {
return new RxAsync<>(rxObservable);
}
@Override
public void subscribe(final AsyncObserver observer) {
if (canceled) {
return;
}
subscription = rxObservable.subscribe(new Subscriber() {
@Override
public void onCompleted() {
observer.onReset();
}
@Override
public void onError(final Throwable e) {
observer.onError(e);
}
@Override
public void onNext(final D d) {
observer.onResult(d);
}
});
}
@Override
public void cancel() {
canceled = true;
if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
}
}
}