cyclops.reactive.FlowableManaged Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cyclops-rx2-integration Show documentation
Show all versions of cyclops-rx2-integration Show documentation
Cyclops integration with RxJava 2
package cyclops.reactive;
import com.oath.cyclops.util.ExceptionSoftener;
import cyclops.control.Future;
import cyclops.control.Try;
import cyclops.data.Seq;
import cyclops.function.Monoid;
import cyclops.function.Semigroup;
import org.reactivestreams.Publisher;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static cyclops.reactive.FlowableIO.*;
public abstract class FlowableManaged extends Managed {
public static Managed managed(T just,Consumer cleanup){
return Managed.of(just(just),cleanup);
}
public static Managed of(Supplier extends T> s, Consumer cleanup){
return Managed.of(FlowableIO.of(s),cleanup);
}
public static Managed managed(T just){
return Managed.of(just(just));
}
public static Managed of(Supplier extends T> s){
return Managed.of(FlowableIO.of(s));
}
public static Managed of(Publisher acq){
return Managed.of(FlowableIO.fromPublisher(acq), ExceptionSoftener.softenConsumer(c->c.close()));
}
public final static Semigroup> semigroup(Semigroup s){
return (a,b) -> a.flatMap(t1 -> b.map(t2 -> s.apply(t1, t2)));
}
public final static Monoid> monoid(Monoid s){
return Monoid.of(managed(s.zero(),__->{}),semigroup(s));
}
public static Managed of(IO acquire, Consumer cleanup){
return new FlowableManaged(){
public IO apply(Function super T,? extends IO> fn){
IO y = IO.Comprehensions.forEach(acquire, t1 -> {
IO extends Try extends IO, Throwable>> res1 = FlowableIO.withCatch(() -> fn.apply(t1), Throwable.class);
return res1;
}, t2 -> {
Try extends IO, Throwable> tr = t2._2();
IO res = tr.fold(r -> r, e -> FlowableIO.of(Future.ofError(e)));
cleanup.accept(t2._1());
return res;
});
return y;
}
};
}
public static Managed of(IO acquire){
return of(acquire,ExceptionSoftener.softenConsumer(c->c.close()));
}
public static Managed> sequence(Iterable extends Managed> all) {
Managed> acc =null;
for(Managed n : all){
if(acc==null)
acc=n.map(Seq::of);
else
acc = acc.zip(n,(a,b)->a.append(b));
}
return acc;
}
public Managed map(Function super T, ? extends R> mapper){
return of(apply(mapper.andThen(IO::of)),__->{});
}
public Managed flatMap(Function super T, cyclops.reactive.Managed> f){
FlowableManaged m = this;
return new IO.SyncIO.SyncManaged(){
@Override
public IO apply(Function super R, ? extends IO> fn) {
IO x = m.apply(r1 -> {
IO r = f.apply(r1).apply(r2 -> fn.apply(r2));
return r;
});
return x;
}
};
}
}