rx.Observable.Transformer Java Examples

The following examples show how to use rx.Observable.Transformer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransformersTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
private static Transformer<Integer, Integer> removePairs() {
    Func1<Integer, Boolean> isCandidateForFirst = new Func1<Integer, Boolean>() {
        @Override
        public Boolean call(Integer t) {
            return t == 1;
        }
    };
    Func2<Integer, Integer, Boolean> remove = new Func2<Integer, Integer, Boolean>() {

        @Override
        public Boolean call(Integer t1, Integer t2) {
            return t1 == 1 && t2 == 2;
        }
    };
    return Transformers.removePairs(isCandidateForFirst, remove);
}
 
Example #2
Source File: MobiusEffectRouterTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void effectHandlersShouldBeImmutable() throws Exception {
  // redo some test setup for test case specific conditions
  publishSubject = PublishSubject.create();
  testSubscriber = TestSubscriber.create();

  RxMobius.SubtypeEffectHandlerBuilder<TestEffect, TestEvent> builder =
      RxMobius.<TestEffect, TestEvent>subtypeEffectHandler()
          .addTransformer(A.class, (Observable<A> as) -> as.map(a -> AEvent.create(a.id())));

  Transformer<TestEffect, TestEvent> router = builder.build();

  // this should not lead to the effects router being capable of handling B effects
  builder.addTransformer(B.class, (Observable<B> bs) -> bs.map(b -> BEvent.create(b.id())));

  publishSubject.compose(router).subscribe(testSubscriber);

  B effect = B.create(84);
  publishSubject.onNext(effect);
  publishSubject.onCompleted();

  testSubscriber.awaitTerminalEvent(3, TimeUnit.SECONDS);
  testSubscriber.assertError(new UnknownEffectException(effect));
}
 
Example #3
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
public static <T> Transformer<T, Set<T>> toSet() {
    return new Transformer<T, Set<T>>() {

        @Override
        public Observable<Set<T>> call(Observable<T> o) {
            return o.collect(new Func0<Set<T>>() {

                @Override
                public Set<T> call() {
                    return new HashSet<T>();
                }
            }, new Action2<Set<T>, T>() {

                @Override
                public void call(Set<T> set, T t) {
                    set.add(t);
                }
            });
        }
    };
}
 
Example #4
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Observable.Transformer} that will flatten the provided {@link Func1} into the
 * stream as an {@link Observable} every time it receives an effect from the upstream effects
 * observable. This will result in calling the function on the specified scheduler, and passing it
 * the requested effect object then emitting its returned value.
 *
 * @param function the {@link Func1} to be invoked every time the effect is requested
 * @param scheduler the {@link Scheduler} to be used when invoking the function
 * @param <F> the type of Effect this transformer handles
 * @param <E> the type of Event this transformer emits
 * @return an {@link Observable.Transformer} that can be used with a {@link
 *     SubtypeEffectHandlerBuilder}.
 */
static <F, E> Observable.Transformer<F, E> fromFunction(
    final Function<F, E> function, @Nullable final Scheduler scheduler) {
  return new Observable.Transformer<F, E>() {
    @Override
    public Observable<E> call(Observable<F> effectStream) {
      return effectStream.flatMap(
          new Func1<F, Observable<E>>() {
            @Override
            public Observable<E> call(final F f) {
              Observable<E> eventObservable =
                  Observable.fromCallable(
                      new Callable<E>() {
                        @Override
                        public E call() throws Exception {
                          return function.apply(f);
                        }
                      });
              return scheduler == null ? eventObservable : eventObservable.subscribeOn(scheduler);
            }
          });
    }
  };
}
 
Example #5
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Transformer} that will flatten the provided {@link Action0} into the stream
 * as a {@link Completable} every time it receives an effect from the upstream effects observable.
 * This Completable will be subscribed on the specified {@link Scheduler}. This will result in
 * calling the provided Action on the specified scheduler every time an effect dispatched to the
 * created effect transformer.
 *
 * @param doEffect {@link Action0} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} that the action should be run on
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return a {@link Transformer} that can be used with an {@link SubtypeEffectHandlerBuilder}
 */
static <F, E> Transformer<F, E> fromAction(
    final Action0 doEffect, @Nullable final Scheduler scheduler) {
  return fromConsumer(
      new Action1<F>() {
        @Override
        public void call(F f) {
          try {
            doEffect.call();
          } catch (Exception e) {
            throw OnErrorThrowable.from(e);
          }
        }
      },
      scheduler);
}
 
Example #6
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscriptionFromTransition() {
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Subscriber<Integer>, Integer> transition = new Func3<Integer, Integer, Subscriber<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Subscriber<Integer> subscriber) {
            subscriber.onNext(123);
            subscriber.unsubscribe();
            return 1;
        }

    };
    Func2<Integer, Observer<Integer>, Boolean> completion = Functions.alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    Observable.just(1, 1, 1).repeat().compose(transformer).subscribe(ts);
    ts.assertValue(123);
    ts.assertCompleted();
    ts.assertUnsubscribed();
}
 
Example #7
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
public static final <T> Transformer<T, T> repeatLast() {
    return new Transformer<T, T>() {

        @Override
        public Observable<T> call(Observable<T> o) {
            return o.materialize().buffer(2, 1)
                    .flatMap(new Func1<List<Notification<T>>, Observable<T>>() {
                        @Override
                        public Observable<T> call(List<Notification<T>> list) {
                            Notification<T> a = list.get(0);
                            if (list.size() == 2 && list.get(1).isOnCompleted()) {
                                return Observable.just(a.getValue()).repeat();
                            } else if (a.isOnError()) {
                                return Observable.error(list.get(0).getThrowable());
                            } else if (a.isOnCompleted()) {
                                return Observable.empty();
                            } else {
                                return Observable.just(a.getValue());
                            }
                        }
                    });
        }
    };
}
 
Example #8
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Returns a {@link Transformer} that returns an {@link Observable} that is
 * a buffering of the source Observable into lists of sequential items that
 * satisfy the condition {@code condition}.
 * 
 * <p>
 * <img src=
 * "https://github.com/davidmoten/rxjava-extras/blob/master/src/docs/toListWhile.png?raw=true"
 * alt="marble diagram">
 * 
 * @param condition
 *            condition function that must return true if an item is to be
 *            part of the list being prepared for emission
 * @param <T>
 *            the generic type of the source Observable
 * @return transformer as above
 */
public static <T> Transformer<T, List<T>> toListWhile(
        final Func2<? super List<T>, ? super T, Boolean> condition) {

    Func0<List<T>> initialState = new Func0<List<T>>() {
        @Override
        public List<T> call() {
            return new ArrayList<T>();
        }
    };

    Action2<List<T>, T> collect = new Action2<List<T>, T>() {

        @Override
        public void call(List<T> list, T n) {
            list.add(n);
        }
    };
    return collectWhile(initialState, collect, condition);
}
 
Example #9
Source File: TransformerOnTerminateResumeTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void mainCompletes() {
    
    Transformer<Integer, Integer> op = new TransformerOnTerminateResume<Integer>(new Func1<Throwable, Observable<Integer>>() {
        @Override
        public Observable<Integer> call(Throwable e) {
            return Observable.just(11);
        }
    }, Observable.just(12));
    
    TestSubscriber<Integer> ts = TestSubscriber.create();
    
    Observable.range(1, 10)
    .compose(op)
    .subscribe(ts);
    
    ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12);
    ts.assertNoErrors();
    ts.assertCompleted();
}
 
Example #10
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T, T> cache(final long duration, final TimeUnit unit,
        final Worker worker) {
    return new Transformer<T, T>() {
        @Override
        public Observable<T> call(Observable<T> o) {
            return Obs.cache(o, duration, unit, worker);
        }
    };
}
 
Example #11
Source File: Database.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private <T> Transformer<T, Boolean> commitOrRollback_(final boolean commit) {
    final QueryUpdate.Builder updateBuilder = createCommitOrRollbackQuery(commit);
    return new Transformer<T, Boolean>() {
        @Override
        public Observable<Boolean> call(Observable<T> source) {
            return updateBuilder.dependsOn(source).count().exists(IS_NON_ZERO);
        }
    };
}
 
Example #12
Source File: Benchmarks.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String splitRxJavaStringTake5() {
    return Observable.just(lines).compose(new Transformer<String, String>() {
        @Override
        public Observable<String> call(Observable<String> o) {
            return StringObservable.split(o, "\n");
        }
    }).take(5).last().toBlocking().last();
}
 
Example #13
Source File: Benchmarks.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String splitRxJavaString() {
    return Observable.just(lines).compose(new Transformer<String, String>() {
        @Override
        public Observable<String> call(Observable<String> o) {
            return StringObservable.split(o, "\n");
        }
    }).last().toBlocking().last();
}
 
Example #14
Source File: Database.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a database transaction for each onNext call. Following database
 * calls will be subscribed on current thread (Schedulers.trampoline()) and
 * share the same {@link Connection} until transaction is rolled back or
 * committed.
 * 
 * @return begin transaction Transformer
 */
public <T> Transformer<T, T> beginTransactionOnNext_() {
    return new Transformer<T, T>() {
        @Override
        public Observable<T> call(Observable<T> source) {
            return beginTransactionOnNext(Database.this, source);
        }
    };
}
 
Example #15
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T,T> reverse() {
    return new Transformer<T,T>() {

        @Override
        public Observable<T> call(Observable<T> source) {
            return Obs.reverse(source);
        }};
}
 
Example #16
Source File: RxMobius.java    From mobius with Apache License 2.0 5 votes vote down vote up
/**
 * Add an {@link Observable.Transformer} for handling effects of a given type. The handler will
 * receive all effect objects that extend the given class.
 *
 * <p>Adding handlers for two effect classes where one is a super-class of the other is
 * considered a collision and is not allowed. Registering the same class twice is also
 * considered a collision.
 *
 * @param effectClass the effect class to handle
 * @param effectHandler the effect handler for the given effect class
 * @param <G> the effect class as a type parameter
 * @return this builder
 * @throws IllegalArgumentException if there is a handler collision
 */
public <G extends F> SubtypeEffectHandlerBuilder<F, E> addTransformer(
    final Class<G> effectClass, final Transformer<G, E> effectHandler) {
  //noinspection ResultOfMethodCallIgnored
  checkNotNull(effectClass);
  //noinspection ResultOfMethodCallIgnored
  checkNotNull(effectHandler);

  for (Class<?> cls : effectPerformerMap.keySet()) {
    if (cls.isAssignableFrom(effectClass) || effectClass.isAssignableFrom(cls)) {
      throw new IllegalArgumentException(
          "Effect classes may not be assignable to each other, collision found: "
              + effectClass.getSimpleName()
              + " <-> "
              + cls.getSimpleName());
    }
  }

  effectPerformerMap.put(
      effectClass,
      new Transformer<F, E>() {
        @Override
        public Observable<E> call(Observable<F> effects) {
          return effects
              .ofType(effectClass)
              .compose(effectHandler)
              .doOnError(onErrorFunction.call(effectHandler));
        }
      });

  return this;
}
 
Example #17
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <A, B, K, C> Transformer<A, C> matchWith(final Observable<B> obs, final Func1<? super A, ? extends K> key1,
        final Func1<? super B,? extends K> key2, final Func2<? super A, ? super B, C> combiner) {
    return new Transformer<A, C>() {

        @Override
        public Observable<C> call(Observable<A> source) {
            return Obs.match(source, obs, key1, key2, combiner);
        }
    };

}
 
Example #18
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T, T> windowMax(final int windowSize,
        final Comparator<? super T> comparator) {
    return new Transformer<T, T>() {
        @Override
        public Observable<T> call(Observable<T> o) {
            return o.lift(new OperatorWindowMinMax<T>(windowSize, comparator, Metric.MAX));
        }
    };
}
 
Example #19
Source File: Bytes.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static Transformer<byte[], byte[]> collect() {
    return new Transformer<byte[], byte[]>() {

        @Override
        public Observable<byte[]> call(Observable<byte[]> source) {
            return source.collect(BosCreatorHolder.INSTANCE, BosCollectorHolder.INSTANCE)
                    .map(BosToArrayHolder.INSTANCE);
        }
    };
}
 
Example #20
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T extends Number> Transformer<T, Statistics> collectStats() {
    return new Transformer<T, Statistics>() {

        @Override
        public Observable<Statistics> call(Observable<T> o) {
            return o.scan(Statistics.create(), Functions.collectStats());
        }
    };
}
 
Example #21
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T extends Comparable<? super T>> Transformer<T, T> sort() {
    return new Transformer<T, T>() {

        @Override
        public Observable<T> call(Observable<T> o) {
            return o.toSortedList().flatMapIterable(Functions.<List<T>> identity());
        }
    };
}
 
Example #22
Source File: TransformerStateMachine.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <State, In, Out> Transformer<In, Out> create(Func0<? extends State> initialState,
        Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
        Func2<? super State, ? super Subscriber<Out>, Boolean> completion,
        BackpressureStrategy backpressureStrategy, int initialRequest) {
    return new TransformerStateMachine<State, In, Out>(initialState, transition, completion,
            backpressureStrategy, initialRequest);
}
 
Example #23
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T, T> sort(final Comparator<? super T> comparator) {
    return new Transformer<T, T>() {

        @Override
        public Observable<T> call(Observable<T> o) {
            return o.toSortedList(Functions.toFunc2(comparator))
                    .flatMapIterable(Functions.<List<T>> identity());
        }
    };
}
 
Example #24
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T, R extends Iterable<?>> Transformer<T, R> collectWhile(final Func0<R> factory,
        final Action2<? super R, ? super T> collect,
        final Func2<? super R, ? super T, Boolean> condition) {
    Func1<R, Boolean> isEmpty = new Func1<R, Boolean>() {
        @Override
        public Boolean call(R collection) {
            return !collection.iterator().hasNext();
        }
    };
    return collectWhile(factory, collect, condition, isEmpty);
}
 
Example #25
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T, T> windowMin(final int windowSize,
        final Comparator<? super T> comparator) {
    return new Transformer<T, T>() {
        @Override
        public Observable<T> call(Observable<T> o) {
            return o.lift(new OperatorWindowMinMax<T>(windowSize, comparator, Metric.MIN));
        }
    };
}
 
Example #26
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <State, In, Out> Transformer<In, Out> stateMachine(
        Func0<State> initialStateFactory,
        Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
        Func2<? super State, ? super Subscriber<Out>, Boolean> completion,
        BackpressureStrategy backpressureStrategy, int initialRequest) {
    return TransformerStateMachine.<State, In, Out> create(initialStateFactory, transition,
            completion, backpressureStrategy, initialRequest);
}
 
Example #27
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Transformer<T, T> onBackpressureBufferToFile(
        final DataSerializer<T> serializer, final Scheduler scheduler, final Options options) {
    return new Transformer<T, T>() {
        @Override
        public Observable<T> call(Observable<T> o) {
            return o.lift(new OperatorBufferToFile<T>(serializer, scheduler, options));
        }
    };
}
 
Example #28
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
public static Transformer<String, String> split(String pattern) {
    return TransformerStringSplit.split(pattern, null);
}
 
Example #29
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
public static <T> Transformer<T, T> onBackpressureBufferToFile() {
    return onBackpressureBufferToFile(DataSerializers.<T> javaIO(), Schedulers.computation(),
            Options.defaultInstance());
}
 
Example #30
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
public static <T> Transformer<T, T> sampleFirst(final long duration, final TimeUnit unit) {
    return sampleFirst(duration, unit, Schedulers.computation());
}