|
| 1 | +package elasta.composer.utils; |
| 2 | + |
| 3 | +import elasta.commons.Utils; |
| 4 | +import elasta.core.intfs.CallableUnckd; |
| 5 | +import io.reactivex.Observable; |
| 6 | +import io.reactivex.Single; |
| 7 | +import io.reactivex.functions.Function; |
| 8 | +import io.reactivex.functions.Predicate; |
| 9 | +import io.reactivex.subjects.PublishSubject; |
| 10 | + |
| 11 | +import java.util.Objects; |
| 12 | + |
| 13 | +/** |
| 14 | + * Created by sohan on 2017-09-02. |
| 15 | + */ |
| 16 | +@FunctionalInterface |
| 17 | +public interface ReactiveLoop<T> { |
| 18 | + Observable<T> start(); |
| 19 | + |
| 20 | + static <T> ReactiveLoop<T> create(CreateParams<T> params) { |
| 21 | + return () -> { |
| 22 | + try { |
| 23 | + final PublishSubject<T> subject = PublishSubject.create(); |
| 24 | + |
| 25 | + params.initialState.call() |
| 26 | + .doOnEvent((t, throwable) -> handle(t, throwable, subject)) |
| 27 | + .subscribe(); |
| 28 | + |
| 29 | + return subject |
| 30 | + .doOnNext(t -> { |
| 31 | + |
| 32 | + if (Utils.not(params.hasNext.test(t))) { |
| 33 | + subject.onComplete(); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + params.nextState.apply(t) |
| 38 | + .doOnEvent((newState, throwable) -> handle(newState, throwable, subject)) |
| 39 | + .subscribe(); |
| 40 | + |
| 41 | + }); |
| 42 | + } catch (Throwable ex) { |
| 43 | + return Observable.error(ex); |
| 44 | + } |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | + static <T> void handle(T state, Throwable throwable, PublishSubject<T> subject) { |
| 49 | + if (throwable != null) { |
| 50 | + subject.onError(throwable); |
| 51 | + } else { |
| 52 | + subject.onNext(state); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + final class CreateParams<T> { |
| 58 | + private final CallableUnckd<Single<T>> initialState; |
| 59 | + private final Predicate<T> hasNext; |
| 60 | + private final Function<T, Single<T>> nextState; |
| 61 | + |
| 62 | + public CreateParams(CallableUnckd<Single<T>> initialState, Predicate<T> hasNext, Function<T, Single<T>> nextState) { |
| 63 | + Objects.requireNonNull(initialState); |
| 64 | + Objects.requireNonNull(hasNext); |
| 65 | + Objects.requireNonNull(nextState); |
| 66 | + this.initialState = initialState; |
| 67 | + this.hasNext = hasNext; |
| 68 | + this.nextState = nextState; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments