netflix.ocelli.InstanceCollector Maven / Gradle / Ivy
package netflix.ocelli;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import rx.Observable;
import rx.Observable.Transformer;
import rx.functions.Func0;
import rx.functions.Func1;
/**
* From a list of Instance maintain a List of active T. Add when T is up and remove
* when T is either down or Instance failed or completed.
*
* @author elandau
*
* @param
*
* TODO: Use scan()
*/
public class InstanceCollector implements Transformer, List> {
public static InstanceCollector create() {
return new InstanceCollector();
}
@Override
public Observable> call(Observable> o) {
final Set instances = new HashSet();
return o.flatMap(new Func1, Observable>>() {
@Override
public Observable> call(final Instance instance) {
return instance.flatMap(
new Func1>>() {
@Override
public Observable> call(Boolean isUp) {
if (isUp) {
if (instances.add(instance.getValue())) {
return Observable.>just(new ArrayList(instances));
}
}
else {
if (instances.remove(instance.getValue())) {
return Observable.>just(new ArrayList(instances));
}
}
return Observable.empty();
}
},
new Func1>>() {
@Override
public Observable> call(Throwable t1) {
if (instances.remove(instance.getValue())) {
return Observable.>just(new ArrayList(instances));
}
return Observable.empty();
}
},
new Func0>>() {
@Override
public Observable> call() {
if (instances.remove(instance.getValue())) {
return Observable.>just(new ArrayList(instances));
}
return Observable.empty();
}
});
}
});
}
}