netflix.ocelli.InstanceSubject Maven / Gradle / Ivy
package netflix.ocelli;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import rx.Observable;
import rx.Subscriber;
import rx.subjects.PublishSubject;
/**
* @author elandau
*/
public class InstanceSubject extends Observable> {
private final PublishSubject> subject;
private final ConcurrentMap> instances;
public static InstanceSubject create() {
return new InstanceSubject();
}
public InstanceSubject() {
this(PublishSubject.>create(), new ConcurrentHashMap>());
}
private InstanceSubject(final PublishSubject> subject, final ConcurrentMap> instances) {
super(new OnSubscribe>() {
@Override
public void call(Subscriber super Instance> s) {
Observable
.from(new ArrayList>(instances.values()))
.concatWith(subject).subscribe(s);
}
});
this.subject = subject;
this.instances = instances;
}
public MutableInstance add(T t) {
MutableInstance member = MutableInstance.from(t);
MutableInstance existing = instances.putIfAbsent(t, member);
if (null == existing) {
subject.onNext(member);
return member;
}
return existing;
}
public MutableInstance remove(T t) {
MutableInstance member = instances.remove(t);
if (member != null) {
member.close();
}
return member;
}
public void clear() {
for (MutableInstance instance : instances.values()) {
instance.close();
}
instances.clear();
}
}