All Downloads are FREE. Search and download functionalities are using the official Maven repository.

netflix.ocelli.InstanceSubject Maven / Gradle / Ivy

There is a newer version: 0.1.0-rc.2
Show newest version
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> 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();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy