
rx.internal.operators.OperatorMapNotification Maven / Gradle / Ivy
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.internal.operators;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import rx.Observable.Operator;
import rx.Producer;
import rx.Subscriber;
import rx.Subscription;
import rx.exceptions.MissingBackpressureException;
import rx.exceptions.OnErrorThrowable;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.internal.util.unsafe.SpscArrayQueue;
import rx.internal.util.unsafe.UnsafeAccess;
/**
* Applies a function of your choosing to every item emitted by an {@code Observable}, and emits the results of
* this transformation as a new {@code Observable}.
*
*
*/
public final class OperatorMapNotification implements Operator {
private final Func1 super T, ? extends R> onNext;
private final Func1 super Throwable, ? extends R> onError;
private final Func0 extends R> onCompleted;
public OperatorMapNotification(Func1 super T, ? extends R> onNext, Func1 super Throwable, ? extends R> onError, Func0 extends R> onCompleted) {
this.onNext = onNext;
this.onError = onError;
this.onCompleted = onCompleted;
}
@Override
public Subscriber super T> call(final Subscriber super R> o) {
Subscriber subscriber = new Subscriber() {
SingleEmitter emitter;
@Override
public void setProducer(Producer producer) {
emitter = new SingleEmitter(o, producer, this);
o.setProducer(emitter);
}
@Override
public void onCompleted() {
try {
emitter.offerAndComplete(onCompleted.call());
} catch (Throwable e) {
o.onError(e);
}
}
@Override
public void onError(Throwable e) {
try {
emitter.offerAndComplete(onError.call(e));
} catch (Throwable e2) {
o.onError(e);
}
}
@Override
public void onNext(T t) {
try {
emitter.offer(onNext.call(t));
} catch (Throwable e) {
o.onError(OnErrorThrowable.addValueAsLastCause(e, t));
}
}
};
o.add(subscriber);
return subscriber;
}
static final class SingleEmitter extends AtomicLong implements Producer, Subscription {
/** */
private static final long serialVersionUID = -249869671366010660L;
final NotificationLite nl;
final Subscriber super T> child;
final Producer producer;
final Subscription cancel;
final Queue