Java Code Examples for io.reactivex.functions.Function#apply()

The following examples show how to use io.reactivex.functions.Function#apply() . 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: RxMobius.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Optionally set a shared error handler in case a handler throws an uncaught exception.
 *
 * <p>The default is to use {@link RxJavaPlugins#onError(Throwable)}. Note that any exception
 * thrown by a handler is a fatal error and this method doesn't enable safe error handling, only
 * configurable crash reporting.
 *
 * @param function a function that gets told which sub-transformer failed and should return an
 *     appropriate handler for exceptions thrown.
 */
public SubtypeEffectHandlerBuilder<F, E> withFatalErrorHandler(
    final Function<ObservableTransformer<? extends F, E>, Consumer<Throwable>> function) {
  checkNotNull(function);

  this.onErrorFunction =
      new OnErrorFunction<ObservableTransformer<? extends F, E>, Consumer<Throwable>>() {
        @Override
        public Consumer<Throwable> apply(ObservableTransformer<? extends F, E> effectHandler) {
          try {
            return function.apply(effectHandler);
          } catch (Exception e) {
            throw new RuntimeException(
                "FATAL: fatal error handler threw exception for effect handler: "
                    + effectHandler,
                e);
          }
        }
      };

  return this;
}
 
Example 2
Source File: Call.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
private static <T> Flowable<T> createFlowable(NamedCallableStatement stmt,
        Function<? super ResultSet, ? extends T> f) throws SQLException {
    ResultSet rsActual = stmt.stmt.getResultSet();
    Callable<ResultSet> initialState = () -> rsActual;
    BiConsumer<ResultSet, Emitter<T>> generator = (rs, emitter) -> {
        log.debug("getting row from ps={}, rs={}", stmt.stmt, rs);
        if (rs.next()) {
            T v = f.apply(rs);
            log.debug("emitting {}", v);
            emitter.onNext(v);
        } else {
            log.debug("completed");
            emitter.onComplete();
        }
    };
    Consumer<ResultSet> disposeState = Util::closeSilently;
    return Flowable.generate(initialState, generator, disposeState);
}
 
Example 3
Source File: RxAndroidPlugins.java    From atlas with Apache License 2.0 5 votes vote down vote up
static <T, R> R apply(Function<T, R> f, T t) {
    try {
        return f.apply(t);
    } catch (Throwable ex) {
        throw Exceptions.propagate(ex);
    }
}
 
Example 4
Source File: Transformers.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
/**
 * Buffers the source {@link Flowable} into {@link List}s, emitting Lists when
 * the size of a list reaches {@code maxSize} or if the elapsed time since last
 * emission from the source reaches the given duration.
 * 
 * @param maxSize
 *            max size of emitted lists
 * @param duration
 *            function that based on the last emission calculates the elapsed
 *            time to be used before emitting a buffered list
 * @param unit
 *            unit of {@code duration}
 * @param scheduler
 *            scheduler to use to schedule emission of a buffer (as a list) if
 *            the time since last emission from the source reaches duration
 * @param <T>
 *            type of the source stream items
 * @return source with operator applied
 */
public static <T> FlowableTransformer<T, List<T>> buffer(final int maxSize,
        final Function<? super T, ? extends Long> duration, final TimeUnit unit, final Scheduler scheduler) {

    final BiPredicate<List<T>, MyOptional<T>> condition = new BiPredicate<List<T>, MyOptional<T>>() {
        @Override
        public boolean test(List<T> list, MyOptional<T> x) throws Exception {
            return list.size() < maxSize && x.isPresent();
        }
    };
    Function<MyOptional<T>, Long> timeout = new Function<MyOptional<T>, Long>() {
        @Override
        public Long apply(MyOptional<T> t) throws Exception {
            return duration.apply(t.get());
        }
    };
    final FlowableTransformer<MyOptional<T>, MyOptional<T>> insert = insert(timeout, unit,
            Functions.constant(MyOptional.<T>empty()), scheduler);

    final FlowableTransformer<MyOptional<T>, List<T>> collectWhile = collectWhile( //
            // factory
            ListFactoryHolder.<T>factory(), //
            // add function
            MyOptional.<T>addIfPresent(), //
            // condition
            condition);

    return new FlowableTransformer<T, List<T>>() {
        @Override
        public Publisher<List<T>> apply(Flowable<T> source) {

            return source //
                    .map(MyOptional.<T>of()) //
                    .compose(insert) //
                    .compose(collectWhile)
                    // need this filter because sometimes nothing gets added to list
                    .filter(MyOptional.<T>listHasElements()); //
        }
    };
}
 
Example 5
Source File: StateMachineFactory.java    From state-machine with Apache License 2.0 5 votes vote down vote up
@Override
public EntityBehaviour<?, Id> apply(Class<?> cls) throws Exception {
    Function<Class<?>, EntityBehaviour<?, Id>> f = map.get(cls);
    if (f != null) {
        return f.apply(cls);
    } else {
        throw new RuntimeException("state machine factory not defined for " + cls);
    }
}
 
Example 6
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}
 
Example 7
Source File: RequestContextAssembly.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static <T> Function<? super T, ? extends T> compose(
        @Nullable Function<? super T, ? extends T> before,
        Function<? super T, ? extends T> after) {
    if (before == null) {
        return after;
    }
    return (T v) -> after.apply(before.apply(v));
}
 
Example 8
Source File: NullAwayRxSupportNegativeCases.java    From NullAway with MIT License 4 votes vote down vote up
private static <T, R> R funcapply(Function<T, R> f, T val) throws Exception {
  return f.apply(val);
}
 
Example 9
Source File: NullAwayJava8PositiveCases.java    From NullAway with MIT License 4 votes vote down vote up
static <R, T> R map(T t, Function<T, R> fun) {
  return fun.apply(t);
}
 
Example 10
Source File: Select.java    From rxjava2-jdbc with Apache License 2.0 4 votes vote down vote up
private static <T> Flowable<? extends T> create(PreparedStatement ps, List<Object> parameters,
                                                Function<? super ResultSet, T> mapper, List<String> names, String sql, int fetchSize, int queryTimeoutSec) {
    log.debug("parameters={}", parameters);
    log.debug("names={}", names);

    Callable<ResultSet> initialState = () -> {
        List<Parameter> params = Util.toParameters(parameters);
        boolean hasCollection = params.stream().anyMatch(x -> x.isCollection());
        final PreparedStatement ps2;
        if (hasCollection) {
            // create a new prepared statement with the collection ? substituted with
            // ?s to match the size of the collection parameter
            ps2 = Util.prepare(ps.getConnection(), fetchSize, sql, params, queryTimeoutSec);
            // now wrap the rs to auto close ps2 because it is single use (the next
            // collection parameter may have a different ordinality so we need to build
            // a new PreparedStatement with a different number of question marks
            // substituted
            return new ResultSetAutoClosesStatement(Util //
                    .setParameters(ps2, params, names) //
                    .executeQuery(), ps2);
        } else {
            // use the current prepared statement (normal re-use)
            ps2 = ps;
            return Util //
                    .setParameters(ps2, params, names) //
                    .executeQuery();
        }
    };
    BiConsumer<ResultSet, Emitter<T>> generator = (rs, emitter) -> {
        log.debug("getting row from ps={}, rs={}", rs.getStatement(), rs);
        if (rs.next()) {
            T v = mapper.apply(rs);
            log.debug("emitting {}", v);
            emitter.onNext(v);
        } else {
            log.debug("completed");
            emitter.onComplete();
        }
    };
    Consumer<ResultSet> disposeState = Util::closeSilently;
    return Flowable.generate(initialState, generator, disposeState);
}