rx.marble.HotObservable Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of marbletest4j Show documentation
Show all versions of marbletest4j Show documentation
Java port of RxJS marble tests
package rx.marble;
import rx.Notification;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class HotObservable extends Observable implements TestableObservable {
private final List>> notifications;
List subscriptions = new ArrayList<>();
protected HotObservable(OnSubscribe f, List>> notifications) {
super(f);
this.notifications = notifications;
}
@Override
public List getSubscriptions() {
return Collections.unmodifiableList(subscriptions);
}
@Override
public List>> getMessages() {
return Collections.unmodifiableList(notifications);
}
public static HotObservable create(Scheduler scheduler, Recorded>... notifications) {
return create(scheduler, Arrays.asList(notifications));
}
public static HotObservable create(Scheduler scheduler, List>> notifications) {
OnSubscribeHandler onSubscribeFunc = new OnSubscribeHandler<>(scheduler, notifications);
HotObservable observable = new HotObservable<>(onSubscribeFunc, notifications);
onSubscribeFunc.observable = observable;
return observable;
}
private static class OnSubscribeHandler implements Observable.OnSubscribe {
private final Scheduler scheduler;
private final List> subscribers = new ArrayList<>();
public HotObservable observable;
public OnSubscribeHandler(Scheduler scheduler, List>> notifications) {
this.scheduler = scheduler;
Scheduler.Worker worker = scheduler.createWorker();
for (final Recorded> event : notifications) {
worker.schedule(new Action0() {
@Override
public void call() {
List> subscribers
= new ArrayList<>(OnSubscribeHandler.this.subscribers);
for (Subscriber super T> subscriber : subscribers){
event.value.accept(subscriber);
}
}
}, event.time, TimeUnit.MILLISECONDS);
}
}
public void call(final Subscriber super T> subscriber) {
final SubscriptionLog subscriptionLog = new SubscriptionLog(scheduler.now());
observable.subscriptions.add(subscriptionLog);
final int subscriptionIndex = observable.getSubscriptions().size() - 1;
subscribers.add(subscriber);
subscriber.add((Subscriptions.create(new Action0() {
@Override
public void call() {
// on unsubscribe
observable.subscriptions.set(
subscriptionIndex,
new SubscriptionLog(subscriptionLog.subscribe, scheduler.now())
);
subscribers.remove(subscriber);
}
})));
}
}
}