From 54adc1ed1a31549219412b7d4cee133b84239252 Mon Sep 17 00:00:00 2001 From: Ben Christensen <benjchristensen@netflix.com> Date: Fri, 21 Feb 2014 14:09:51 -0800 Subject: [PATCH] Operator: doOnTerminate Like finallyDo but before emitting the terminal state instead of after. --- rxjava-core/src/main/java/rx/Observable.java | 39 ++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java index 2224fa3c8e..dc47e9175f 100644 --- a/rxjava-core/src/main/java/rx/Observable.java +++ b/rxjava-core/src/main/java/rx/Observable.java @@ -4293,17 +4293,17 @@ public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNot Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { - onNotification.call(new Notification<T>()); + onNotification.call(Notification.createOnCompleted()); } @Override public final void onError(Throwable e) { - onNotification.call(new Notification<T>(e)); + onNotification.call(Notification.createOnError(e)); } @Override public final void onNext(T v) { - onNotification.call(new Notification<T>(v)); + onNotification.call(Notification.createOnNext(v)); } }; @@ -4387,6 +4387,39 @@ public final void onNext(T args) { return lift(new OperatorDoOnEach<T>(observer)); } + + /** + * Modifies an Observable so that it invokes an action when it calls {@code onCompleted} or {@code onError} <p> + * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/doOnCompleted.png"> + * <p> + * This differs from {@code finallyDo} in that this happens BEFORE onCompleted/onError are emitted. + * + * @param onTerminate + * the action to invoke when the source Observable calls {@code onCompleted} or {@code onError} + * @return the source Observable with the side-effecting behavior applied + * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#wiki-dooncompleted">RxJava Wiki: doOnCompleted()</a> + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229804.aspx">MSDN: Observable.Do</a> + */ + public final Observable<T> doOnTerminate(final Action0 onTerminate) { + Observer<T> observer = new Observer<T>() { + @Override + public final void onCompleted() { + onTerminate.call(); + } + + @Override + public final void onError(Throwable e) { + onTerminate.call(); + } + + @Override + public final void onNext(T args) { + } + + }; + + return lift(new OperatorDoOnEach<T>(observer)); + } /** * Returns an Observable that emits the single item at a specified index in a sequence of emissions from a