Java Code Examples for io.reactivex.Flowable#defer()

The following examples show how to use io.reactivex.Flowable#defer() . 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: DataSetTableRepositoryImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Flowable<State> dataSetState(){
    return Flowable.defer(() ->{
        State state;
        DataSetInstance dataSetInstance = d2.dataSetModule().dataSetInstances()
                .byDataSetUid().eq(dataSetUid)
                .byAttributeOptionComboUid().eq(catOptCombo)
                .byOrganisationUnitUid().eq(orgUnitUid)
                .byPeriod().eq(periodId).one().blockingGet();

        state = dataSetInstance.state();

        DataSetCompleteRegistration dscr = d2.dataSetModule().dataSetCompleteRegistrations()
                .byDataSetUid().eq(dataSetUid)
                .byAttributeOptionComboUid().eq(catOptCombo)
                .byOrganisationUnitUid().eq(orgUnitUid)
                .byPeriod().eq(periodId).one().blockingGet();

        if(state == State.SYNCED && dscr!=null){
            state = dscr.state();
        }

        return state != null ? Flowable.just(state) : Flowable.empty();
    });
}
 
Example 2
Source File: UserPostTableConnection.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
public static Flowable<Boolean> removePost(final String boardName, final long threadId, final long postId) {

        return Flowable.defer((Callable<Flowable<Boolean>>) () -> {
            long val = 0;
            BriteDatabase db = MimiApplication.getInstance().getBriteDatabase();
            BriteDatabase.Transaction transaction = db.newTransaction();

            try {
                UserPost userPost = new UserPost();
                userPost.boardName = boardName;
                userPost.threadId = threadId;
                userPost.postId = postId;
                userPost.postTime = System.currentTimeMillis();

                val = DatabaseUtils.delete(db, userPost);

                transaction.markSuccessful();
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error saving user post data", e);
            } finally {
                transaction.end();
            }
            return Flowable.just(val > 0);
        });
    }
 
Example 3
Source File: UserPostTableConnection.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
public static Flowable<Boolean> addPost(final String boardName, final long threadId, final long postId) {

        return Flowable.defer((Callable<Flowable<Boolean>>) () -> {
            long val = 0;
            BriteDatabase db = MimiApplication.getInstance().getBriteDatabase();
            BriteDatabase.Transaction transaction = db.newTransaction();

            try {
                UserPost userPost = new UserPost();
                userPost.boardName = boardName;
                userPost.threadId = threadId;
                userPost.postId = postId;
                userPost.postTime = System.currentTimeMillis();

                val = DatabaseUtils.insert(db, userPost);

                transaction.markSuccessful();
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error saving user post data", e);
            } finally {
                transaction.end();
            }
            return Flowable.just(val > 0);
        });
    }
 
Example 4
Source File: TransactedSelectAutomappedBuilder.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
private static <T> Flowable<Tx<T>> createFlowable(SelectAutomappedBuilder<T> sb, Database db) {
    return Flowable.defer(() -> {
        AtomicReference<Connection> connection = new AtomicReference<Connection>();
        return Select.create(sb.selectBuilder.connection //
                .map(c -> Util.toTransactedConnection(connection, c)), //
                sb.selectBuilder.parameterGroupsToFlowable(), //
                sb.selectBuilder.sql, //
                sb.selectBuilder.fetchSize, //
                Util.autoMap(sb.cls), //
                false, //
                sb.selectBuilder.queryTimeoutSec) //
                .materialize() //
                .flatMap(n -> Tx.toTx(n, connection.get(), db)) //
                .doOnNext(tx -> {
                    if (tx.isComplete()) {
                        ((TxImpl<T>) tx).connection().commit();
                    }
                });
    });
}
 
Example 5
Source File: TransactedCallableBuilder.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
private static <T> Flowable<Tx<T>> inTransaction(CallableBuilder b,
        Function<Single<Connection>, Flowable<Notification<T>>> f) {
    return Flowable.defer(() -> {
        AtomicReference<Connection> con = new AtomicReference<Connection>();
        // set the atomic reference when transactedConnection emits
        Single<Connection> transactedConnection = b.connection //
                .map(c -> Util.toTransactedConnection(con, c));
        return f.apply(transactedConnection) //
                .<Tx<T>>flatMap(n -> Tx.toTx(n, con.get(), b.db)) //
                .doOnNext(tx -> {
                    if (tx.isComplete()) {
                        ((TxImpl<T>) tx).connection().commit();
                    }
                });
    });
}
 
Example 6
Source File: TransactedReturnGeneratedKeysBuilder.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms the results using the given function.
 *
 * @param mapper
 *            maps the query results to an object
 * @return the results of the query as an Observable
 */
@Override
public <T> Flowable<Tx<T>> get(@Nonnull ResultSetMapper<? extends T> mapper) {
    Preconditions.checkNotNull(mapper, "mapper cannot be null");
    return Flowable.defer(() -> {
        AtomicReference<Connection> connection = new AtomicReference<Connection>();
        Flowable<T> o = Update.<T>createReturnGeneratedKeys( //
                update.updateBuilder.connections //
                        .map(c -> Util.toTransactedConnection(connection, c)),
                update.parameterGroupsToFlowable(), update.updateBuilder.sql, mapper, false);
        return o.materialize() //
                .flatMap(n -> Tx.toTx(n, connection.get(), db)) //
                .doOnNext(tx -> {
                    if (tx.isComplete()) {
                        ((TxImpl<T>) tx).connection().commit();
                    }
                });
    });
}
 
Example 7
Source File: TransactedSelectBuilder.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Flowable<Tx<T>> createFlowable(SelectBuilder sb,
        ResultSetMapper<? extends T> mapper, Database db) {
    return (Flowable<Tx<T>>) (Flowable<?>) Flowable.defer(() -> {
        //Select.<T>create(connection, pg, sql, fetchSize, mapper, true);
        AtomicReference<Connection> connection = new AtomicReference<Connection>();
        Single<Connection> con = sb.connection //
                .map(c -> Util.toTransactedConnection(connection, c));
        return Select.create(con, //
                sb.parameterGroupsToFlowable(), //
                sb.sql, //
                sb.fetchSize, //
                mapper, //
                false, //
                sb.queryTimeoutSec) //
                .materialize() //
                .flatMap(n -> Tx.toTx(n, connection.get(), db)) //
                .doOnNext(tx -> {
                    if (tx.isComplete()) {
                        ((TxImpl<T>) tx).connection().commit();
                    }
                });
    });
}
 
Example 8
Source File: Compressor.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<File> compressToFileAsFlowable(final File imageFile, final String compressedFileName) {
    return Flowable.defer((Callable<Flowable<File>>) () -> {
        try {
            return Flowable.just(compressToFile(imageFile, compressedFileName));
        } catch (IOException e) {
            return Flowable.error(e);
        }
    });
}
 
Example 9
Source File: Processor.java    From state-machine with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public Flowable<EntityStateMachine<?, Id>> flowable() {
    return Flowable.defer(() -> {
        Worker worker = signalScheduler.createWorker();
        Flowable<Signal<?, Id>> o0 = subject //
                .toSerialized() //
                .toFlowable(BackpressureStrategy.BUFFER) //
                .mergeWith(signals) //
                .doOnCancel(() -> worker.dispose()) //
                .compose(preGroupBy);
        Flowable<GroupedFlowable<ClassId<?, Id>, Signal<?, Id>>> o;
        if (mapFactory != null) {
            o = o0.groupBy(signal -> new ClassId(signal.cls(),
             signal.id()), x -> x, true, 16, mapFactory);
        } else {
            o = o0.groupBy(signal -> new ClassId(signal.cls(), signal.id()),
                    Functions.identity());
        }
        return o.flatMap(g -> {
            Flowable<EntityStateMachine<?, Id>> obs = g //
                    .flatMap(processSignalsToSelfAndSendSignalsToOthers(worker, g.getKey())) //
                    .doOnNext(m -> stateMachines.put(g.getKey(), m)) //
                    .subscribeOn(processingScheduler); //

            Flowable<EntityStateMachine<?, Id>> res = entityTransform
                    .apply(grouped(g.getKey(), obs));
            return res;
        });
    });
}
 
Example 10
Source File: DatabaseUtils.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public static <K extends BaseModel> Flowable<Boolean> remove(final K model, WhereArg wheres) {

        return Flowable.defer((Callable<Flowable<Boolean>>) () -> {
            BriteDatabase db = MimiApplication.getInstance().getBriteDatabase();
            long val = db.delete(model.getTableName(), wheres.where, wheres.where);

            return Flowable.just(val >= 0);
        });
    }
 
Example 11
Source File: DatabaseUtils.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public static <K extends BaseModel> Flowable<Boolean> insert(final List<K> models) {

        return Flowable.defer((Callable<Flowable<Boolean>>) () -> {
            long val = insertModels(models);
            return Flowable.just(val > 0);
        });
    }
 
Example 12
Source File: HistoryTableConnection.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public static Flowable<Boolean> setHistoryRemovedStatus(final String boardName, final long threadId, final boolean removed) {
    return Flowable.defer((Callable<Flowable<Boolean>>) () -> {

        BriteDatabase db = MimiApplication.getInstance().getBriteDatabase();
        BriteDatabase.Transaction transaction = db.newTransaction();

        int val = 0;

        try {
            ContentValues values = new ContentValues();
            values.put(History.KEY_THREAD_REMOVED, removed);

            val = db.update(History.TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, values, History.KEY_THREAD_ID + "=?", String.valueOf(threadId));
            transaction.markSuccessful();
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error deleting history: name=" + boardName + ", thread=" + threadId, e);
        } finally {
            transaction.end();
        }

        return Flowable.just(val > 0)
                .onErrorReturn(throwable -> {
                    Log.e(LOG_TAG, "Error deleting history: name=" + boardName + ", thread=" + threadId, throwable);
                    return false;
                })
                .compose(DatabaseUtils.<Boolean>applySchedulers());
    });
}
 
Example 13
Source File: Update.java    From rxjava2-jdbc with Apache License 2.0 5 votes vote down vote up
private static Flowable<Integer> createExecuteBatch(NamedPreparedStatement ps,
        List<Object> parameters) {
    return Flowable.defer(() -> {
        Util.convertAndSetParameters(ps.ps, parameters, ps.names);
        ps.ps.addBatch();
        log.debug("batch added with {}", parameters);
        Flowable<Integer> o = toFlowable(ps.ps.executeBatch());
        log.debug("batch executed");
        return o;
    });
}
 
Example 14
Source File: Compressor.java    From RetroMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<Bitmap> compressToBitmapAsFlowable(final File imageFile) {
    return Flowable.defer(() -> {
        try {
            return Flowable.just(compressToBitmap(imageFile));
        } catch (IOException e) {
            return Flowable.error(e);
        }
    });
}
 
Example 15
Source File: Compressor.java    From RetroMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<File> compressToFileAsFlowable(final File imageFile, final String compressedFileName) {
    return Flowable.defer(() -> {
        try {
            return Flowable.just(compressToFile(imageFile, compressedFileName));
        } catch (IOException e) {
            return Flowable.error(e);
        }
    });
}
 
Example 16
Source File: Resizer.java    From Resizer with MIT License 5 votes vote down vote up
/**
 * Get the resized image bitmap as RxJava Flowable.
 * @return A Flowable that emits the resized image bitmap or error.
 */
public Flowable<Bitmap> getResizedBitmapAsFlowable() {
    return Flowable.defer(new Callable<Flowable<Bitmap>>() {
        @Override
        public Flowable<Bitmap> call() {
            try {
                return Flowable.just(getResizedBitmap());
            } catch (IOException e) {
                return Flowable.error(e);
            }
        }
    });
}
 
Example 17
Source File: Resizer.java    From Resizer with MIT License 5 votes vote down vote up
/**
 * Get the resized image file as RxJava Flowable.
 * @return A Flowable that emits the resized image file or error.
 */
public Flowable<File> getResizedFileAsFlowable() {
    return Flowable.defer(new Callable<Flowable<File>>() {
        @Override
        public Flowable<File> call() {
            try {
                return Flowable.just(getResizedFile());
            } catch (IOException e) {
                return Flowable.error(e);
            }
        }
    });
}
 
Example 18
Source File: ProcessorStageFactory.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
public <I, O> ProcessingStage<I, O> create(Engine engine, Stage.ProcessorStage stage) {
    Processor<I, O> processor = Casts.cast(Objects.requireNonNull(
            Objects.requireNonNull(stage).getRsProcessor()));

    return source -> Flowable.defer(() -> {
        Flowable<O> flowable = Flowable.fromPublisher(processor);
        source.safeSubscribe(processor);
        return flowable;
    });
}
 
Example 19
Source File: Compressor.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public Flowable<Bitmap> compressToBitmapAsFlowable(final File imageFile) {
    return Flowable.defer((Callable<Flowable<Bitmap>>) () -> {
        try {
            return Flowable.just(compressToBitmap(imageFile));
        } catch (IOException e) {
            return Flowable.error(e);
        }
    });
}
 
Example 20
Source File: FlowableFetchPagesByRequest.java    From rxjava2-extras with Apache License 2.0 4 votes vote down vote up
public static <T> Flowable<T> create(final BiFunction<? super Long, ? super Long, ? extends Flowable<T>> fetch,
        final long start, final int maxConcurrency) {
    return Flowable.defer(new Callable<Flowable<T>>() {
        @Override
        public Flowable<T> call() throws Exception {
            // need a ReplaySubject because multiple requests can come
            // through before concatEager has established subscriptions to
            // the subject
            final ReplaySubject<Flowable<T>> subject = ReplaySubject.create();
            final AtomicLong position = new AtomicLong(start);
            LongConsumer request = new LongConsumer() {
                @Override
                public void accept(final long n) throws Exception {
                    final long pos = position.getAndAdd(n);
                    if (SubscriptionHelper.validate(n)) {
                        Flowable<T> flowable;
                        try {
                            flowable = fetch.apply(pos, n);
                        } catch (Throwable e) {
                            Exceptions.throwIfFatal(e);
                            subject.onError(e);
                            return;
                        }
                        // reduce allocations by incorporating the onNext
                        // and onComplete actions into the mutable count
                        // object
                        final Count count = new Count(subject, n);
                        flowable = flowable //
                                .doOnNext(count) //
                                .doOnComplete(count);
                        subject.onNext(flowable);
                    }
                }
            };
            return Flowable //
                    .concatEager(subject.serialize() //
                            .toFlowable(BackpressureStrategy.BUFFER), maxConcurrency, 128) //
                    .doOnRequest(request);
        }
    });
}