-
-
Save anonymous/c3112db1f40dec5b529e to your computer and use it in GitHub Desktop.
RxJava - using a custom stateful Operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Maps an emitted item to an Integer designating the item's zero-based index | |
public class IndexOperator<T> implements Observable.Operator<Integer, T> { | |
private int counter; | |
public IndexOperator() { | |
counter = 0; | |
} | |
@Override | |
public Subscriber<? super T> call(final Subscriber<? super Integer> subscriber) { | |
return new Subscriber<T>() { | |
@Override | |
public void onCompleted() { | |
if (!subscriber.isUnsubscribed()) { | |
subscriber.onCompleted(); | |
} | |
} | |
@Override | |
public void onError(Throwable e) { | |
if (!subscriber.isUnsubscribed()) { | |
subscriber.onError(e); | |
} | |
} | |
@Override | |
public void onNext(T t) { | |
if (!subscriber.isUnsubscribed()) { | |
subscriber.onNext(counter); | |
counter++; | |
} | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Observable<Foo> emitter = ...; | |
emitter.lift(new IndexOperator<Foo>).subscribe(new Subscriber<Integer>() {...}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment