com.github.thorbenkuck.network.stream.AbstractEventStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of easy-net Show documentation
Show all versions of easy-net Show documentation
An EventStream driven, simple to use Client/Server framework
package com.github.thorbenkuck.network.stream;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractEventStream implements WritableEventStream {
private final List> subscriptions = new ArrayList<>();
private final List buffer = new ArrayList<>();
private final EventStreamReference reference = new EventStreamReference();
private boolean paused = false;
private boolean disabled = false;
private void publish(T t) {
List> copy;
synchronized (subscriptions) {
copy = new ArrayList<>(subscriptions);
}
dispatch(copy, t);
copy.clear();
}
protected abstract void dispatch(List> subscriptions, T t);
@Override
public void publishError(Throwable throwable) {
List> copy;
synchronized (subscriptions) {
copy = new ArrayList<>(subscriptions);
}
copy.forEach(subscription -> subscription.notify(throwable));
copy.clear();
}
@Override
public synchronized void unPause() {
paused = false;
buffer.forEach(this::publish);
buffer.clear();
}
@Override
public synchronized void pause() {
paused = true;
}
@Override
public void close() {
List> copy;
synchronized (subscriptions) {
copy = new ArrayList<>(subscriptions);
}
copy.forEach(Subscription::cancel);
buffer.clear();
setDisabled(true);
pause();
subscriptions.clear();
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public void push(T t) {
if (isDisabled()) {
return;
}
if (isPaused()) {
buffer.add(t);
} else {
publish(t);
}
}
@Override
public Subscription subscribe(Subscriber subscriber) {
NotifiableSubscription subscription = new SimpleSubscription<>(subscriber, reference);
subscriptions.add(subscription);
subscriber.onSubscribe();
return subscription;
}
@Override
public List> getSubscriptions() {
return subscriptions;
}
@Override
public boolean isDisabled() {
return disabled;
}
@Override
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
private final class EventStreamReference implements Reference> {
@Override
public boolean contains(NotifiableSubscription subscription) {
return subscriptions.contains(subscription);
}
@Override
public void remove(NotifiableSubscription subscription) {
subscriptions.remove(subscription);
}
}
}