Search in sources :

Example 51 with Flowable

use of io.reactivex.Flowable in project rxjava2-jdbc by davidmoten.

the class Call method createFlowable.

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);
}
Also used : BiFunction(io.reactivex.functions.BiFunction) Connection(java.sql.Connection) Tuple2(org.davidmoten.rx.jdbc.tuple.Tuple2) Tuple3(org.davidmoten.rx.jdbc.tuple.Tuple3) BiConsumer(io.reactivex.functions.BiConsumer) Tuple4(org.davidmoten.rx.jdbc.tuple.Tuple4) LoggerFactory(org.slf4j.LoggerFactory) Lists(com.github.davidmoten.guavamini.Lists) Callable(java.util.concurrent.Callable) Single(io.reactivex.Single) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) Flowable(io.reactivex.Flowable) ResultSet(java.sql.ResultSet) CallableResultSet3(org.davidmoten.rx.jdbc.callable.CallableResultSet3) CallableResultSet4(org.davidmoten.rx.jdbc.callable.CallableResultSet4) CallableResultSet1(org.davidmoten.rx.jdbc.callable.CallableResultSet1) CallableResultSet2(org.davidmoten.rx.jdbc.callable.CallableResultSet2) Notification(io.reactivex.Notification) CallableResultSetN(org.davidmoten.rx.jdbc.callable.CallableResultSetN) Logger(org.slf4j.Logger) TupleN(org.davidmoten.rx.jdbc.tuple.TupleN) PreparedStatement(java.sql.PreparedStatement) Consumer(io.reactivex.functions.Consumer) Emitter(io.reactivex.Emitter) OutParameterPlaceholder(org.davidmoten.rx.jdbc.callable.internal.OutParameterPlaceholder) List(java.util.List) ParameterPlaceholder(org.davidmoten.rx.jdbc.callable.internal.ParameterPlaceholder) Function(io.reactivex.functions.Function) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) InParameterPlaceholder(org.davidmoten.rx.jdbc.callable.internal.InParameterPlaceholder) Emitter(io.reactivex.Emitter) ResultSet(java.sql.ResultSet)

Example 52 with Flowable

use of io.reactivex.Flowable in project TumCampusApp by TCA-Team.

the class CafeteriaActivity method onStart.

/**
 * Setup action bar navigation (to switch between cafeterias)
 */
@Override
protected void onStart() {
    super.onStart();
    // Adapter for drop-down navigation
    ArrayAdapter<Cafeteria> adapterCafeterias = new ArrayAdapter<Cafeteria>(this, R.layout.simple_spinner_item_actionbar, android.R.id.text1, mCafeterias) {

        final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);

        @Override
        public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
            View v = inflater.inflate(R.layout.simple_spinner_dropdown_item_actionbar, parent, false);
            Cafeteria c = getItem(position);
            // Set name
            TextView name = v.findViewById(android.R.id.text1);
            // Set address
            TextView address = v.findViewById(android.R.id.text2);
            // Set distance
            TextView dist = v.findViewById(R.id.distance);
            if (c != null) {
                name.setText(c.getName());
                address.setText(c.getAddress());
                dist.setText(Utils.formatDist(c.getDistance()));
            }
            return v;
        }
    };
    Spinner spinner = findViewById(R.id.spinnerToolbar);
    spinner.setAdapter(adapterCafeterias);
    spinner.setOnItemSelectedListener(this);
    Location currLocation = new LocationManager(this).getCurrentOrNextLocation();
    Flowable<List<Cafeteria>> cafeterias = cafeteriaViewModel.getAllCafeterias(currLocation);
    mDisposable.add(cafeterias.subscribe(it -> {
        validateList(it);
        mCafeterias.clear();
        mCafeterias.addAll(it);
        adapterCafeterias.notifyDataSetChanged();
        setCurrentSelectedCafeteria(spinner);
    }, throwable -> Utils.logwithTag("CafeteriaActivity", throwable.getMessage())));
}
Also used : LocationManager(de.tum.in.tumcampusapp.component.other.locations.LocationManager) CafeteriaDetailsSectionFragment.menuToSpan(de.tum.in.tumcampusapp.component.ui.cafeteria.details.CafeteriaDetailsSectionFragment.menuToSpan) ActivityForDownloadingExternal(de.tum.in.tumcampusapp.component.other.generic.activity.ActivityForDownloadingExternal) Bundle(android.os.Bundle) ViewPager(android.support.v4.view.ViewPager) Intent(android.content.Intent) TUMCabeClient(de.tum.in.tumcampusapp.api.app.TUMCabeClient) NonNull(android.support.annotation.NonNull) CafeteriaDetailsSectionsPagerAdapter(de.tum.in.tumcampusapp.component.ui.cafeteria.details.CafeteriaDetailsSectionsPagerAdapter) CafeteriaViewModel(de.tum.in.tumcampusapp.component.ui.cafeteria.details.CafeteriaViewModel) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Flowable(io.reactivex.Flowable) Menu(android.view.Menu) View(android.view.View) AdapterView(android.widget.AdapterView) TcaDb(de.tum.in.tumcampusapp.database.TcaDb) CafeteriaRemoteRepository(de.tum.in.tumcampusapp.component.ui.cafeteria.repository.CafeteriaRemoteRepository) LocationManager(de.tum.in.tumcampusapp.component.other.locations.LocationManager) R(de.tum.in.tumcampusapp.R) LayoutInflater(android.view.LayoutInflater) Collection(java.util.Collection) Const(de.tum.in.tumcampusapp.utils.Const) CafeteriaLocalRepository(de.tum.in.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository) NetUtils(de.tum.in.tumcampusapp.utils.NetUtils) ViewGroup(android.view.ViewGroup) Spinner(android.widget.Spinner) AlertDialog(android.app.AlertDialog) ArrayAdapter(android.widget.ArrayAdapter) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) TextView(android.widget.TextView) Utils(de.tum.in.tumcampusapp.utils.Utils) Location(android.location.Location) Cafeteria(de.tum.in.tumcampusapp.component.ui.cafeteria.model.Cafeteria) ViewGroup(android.view.ViewGroup) Spinner(android.widget.Spinner) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) LayoutInflater(android.view.LayoutInflater) NonNull(android.support.annotation.NonNull) TextView(android.widget.TextView) ArrayList(java.util.ArrayList) List(java.util.List) Cafeteria(de.tum.in.tumcampusapp.component.ui.cafeteria.model.Cafeteria) ArrayAdapter(android.widget.ArrayAdapter) Location(android.location.Location)

Example 53 with Flowable

use of io.reactivex.Flowable in project realm-java by realm.

the class GotchasActivity method testDistinct.

/**
 * Shows how to to be careful when using `distinct()`
 */
private void testDistinct() {
    Flowable<Person> personFlowable = realm.asFlowable().map(realm -> realm.where(Person.class).sort("name").findAll().get(0));
    // distinct() and distinctUntilChanged() uses standard equals with older objects stored in a HashMap.
    // Realm objects auto-update which means the objects stored will also auto-update.
    // This makes comparing against older objects impossible (even if the new object has changed) because the
    // cached object will also have changed.
    // Use a keySelector function to work around this.
    Disposable distinctDisposable = personFlowable.distinct().subscribe(person -> showStatus("distinct(): " + person.getName() + ":" + person.getAge()));
    compositeDisposable.add(distinctDisposable);
    Disposable distinctKeySelectorDisposable = personFlowable.distinct(person -> person.getAge()).subscribe(person -> showStatus("distinct(keySelector): " + person.getName() + ":" + person.getAge()));
    compositeDisposable.add(distinctKeySelectorDisposable);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Realm(io.realm.Realm) Bundle(android.os.Bundle) Random(java.util.Random) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) Person(io.realm.examples.rxjava.model.Person) Flowable(io.reactivex.Flowable) Sort(io.realm.Sort) R(io.realm.examples.rxjava.R) Schedulers(io.reactivex.schedulers.Schedulers) Person(io.realm.examples.rxjava.model.Person)

Example 54 with Flowable

use of io.reactivex.Flowable in project realm-java by realm.

the class RealmResults method asFlowable.

/**
 * Returns an Rx Flowable that monitors changes to this RealmResults. It will emit the current RealmResults when
 * subscribed to. RealmResults will continually be emitted as the RealmResults are updated -
 * {@code onComplete} will never be called.
 * <p>
 * Items emitted from Realm Flowables are frozen (See {@link #freeze()}. This means that they
 * are immutable and can be read on any thread.
 * <p>
 * Realm Flowables always emit items from the thread holding the live RealmResults. This means that if
 * you need to do further processing, it is recommend to observe the values on a computation
 * scheduler:
 * <p>
 * {@code
 * realm.where(Foo.class).findAllAsync().asFlowable()
 *   .observeOn(Schedulers.computation())
 *   .map(rxResults -> doExpensiveWork(rxResults))
 *   .observeOn(AndroidSchedulers.mainThread())
 *   .subscribe( ... );
 * }
 * <p>
 * If you would like the {@code asFlowable()} to stop emitting items you can instruct RxJava to
 * only emit only the first item by using the {@code first()} operator:
 * <p>
 * <pre>
 * {@code
 * realm.where(Foo.class).findAllAsync().asFlowable()
 *      .filter(results -> results.isLoaded())
 *      .first()
 *      .subscribe( ... ) // You only get the results once
 * }
 * </pre>
 * <p>
 *
 * @return RxJava Observable that only calls {@code onNext}. It will never call {@code onComplete}
 * or {@code OnError}.
 * @throws UnsupportedOperationException if the required RxJava framework is not on the classpath or the
 * corresponding Realm instance doesn't support RxJava.
 * @throws IllegalStateException if the Realm wasn't opened on a Looper thread.
 * @see <a href="https://github.com/realm/realm-java/tree/master/examples/rxJavaExample">RxJava and Realm</a>
 */
@SuppressWarnings("unchecked")
public Flowable<RealmResults<E>> asFlowable() {
    if (baseRealm instanceof Realm) {
        return baseRealm.configuration.getRxFactory().from((Realm) baseRealm, this);
    }
    if (baseRealm instanceof DynamicRealm) {
        DynamicRealm dynamicRealm = (DynamicRealm) baseRealm;
        RealmResults<DynamicRealmObject> dynamicResults = (RealmResults<DynamicRealmObject>) this;
        @SuppressWarnings("UnnecessaryLocalVariable") Flowable results = baseRealm.configuration.getRxFactory().from(dynamicRealm, dynamicResults);
        return results;
    } else {
        throw new UnsupportedOperationException(baseRealm.getClass() + " does not support RxJava2.");
    }
}
Also used : Flowable(io.reactivex.Flowable)

Example 55 with Flowable

use of io.reactivex.Flowable in project resilience4j by resilience4j.

the class RateLimiterMethodInterceptor method invoke.

@SuppressWarnings("unchecked")
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    RateLimiter annotation = invocation.getMethod().getAnnotation(RateLimiter.class);
    RecoveryFunction<?> recoveryFunction = annotation.recovery().newInstance();
    if (registry == null) {
        registry = RateLimiterRegistry.ofDefaults();
    }
    io.github.resilience4j.ratelimiter.RateLimiter rateLimiter = registry.rateLimiter(annotation.name());
    if (rateLimiter == null) {
        return invocation.proceed();
    }
    Class<?> returnType = invocation.getMethod().getReturnType();
    if (Promise.class.isAssignableFrom(returnType)) {
        Promise<?> result = (Promise<?>) proceed(invocation, rateLimiter, recoveryFunction);
        if (result != null) {
            RateLimiterTransformer transformer = RateLimiterTransformer.of(rateLimiter).recover(recoveryFunction);
            result = result.transform(transformer);
        }
        return result;
    } else if (Observable.class.isAssignableFrom(returnType)) {
        Observable<?> result = (Observable<?>) proceed(invocation, rateLimiter, recoveryFunction);
        if (result != null) {
            RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
            result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
        }
        return result;
    } else if (Flowable.class.isAssignableFrom(returnType)) {
        Flowable<?> result = (Flowable<?>) proceed(invocation, rateLimiter, recoveryFunction);
        if (result != null) {
            RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
            result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
        }
        return result;
    } else if (Single.class.isAssignableFrom(returnType)) {
        Single<?> result = (Single<?>) proceed(invocation, rateLimiter, recoveryFunction);
        if (result != null) {
            RateLimiterOperator operator = RateLimiterOperator.of(rateLimiter);
            result = result.lift(operator).onErrorReturn(t -> recoveryFunction.apply((Throwable) t));
        }
        return result;
    } else if (CompletionStage.class.isAssignableFrom(returnType)) {
        RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
        Duration timeoutDuration = rateLimiterConfig.getTimeoutDuration();
        if (rateLimiter.getPermission(timeoutDuration)) {
            return proceed(invocation, rateLimiter, recoveryFunction);
        } else {
            final CompletableFuture promise = new CompletableFuture<>();
            Throwable t = new RequestNotPermitted("Request not permitted for limiter: " + rateLimiter.getName());
            try {
                promise.complete(recoveryFunction.apply(t));
            } catch (Throwable t2) {
                promise.completeExceptionally(t2);
            }
            return promise;
        }
    }
    return handleProceedWithException(invocation, rateLimiter, recoveryFunction);
}
Also used : Inject(com.google.inject.Inject) RateLimiterOperator(io.github.resilience4j.ratelimiter.operator.RateLimiterOperator) Promise(ratpack.exec.Promise) CompletableFuture(java.util.concurrent.CompletableFuture) RequestNotPermitted(io.github.resilience4j.ratelimiter.RequestNotPermitted) Single(io.reactivex.Single) RecoveryFunction(io.github.resilience4j.ratpack.recovery.RecoveryFunction) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) MethodInvocation(org.aopalliance.intercept.MethodInvocation) CompletionStage(java.util.concurrent.CompletionStage) Flowable(io.reactivex.Flowable) Duration(java.time.Duration) Observable(io.reactivex.Observable) RateLimiterConfig(io.github.resilience4j.ratelimiter.RateLimiterConfig) RateLimiterRegistry(io.github.resilience4j.ratelimiter.RateLimiterRegistry) RateLimiterConfig(io.github.resilience4j.ratelimiter.RateLimiterConfig) Duration(java.time.Duration) Observable(io.reactivex.Observable) Promise(ratpack.exec.Promise) CompletableFuture(java.util.concurrent.CompletableFuture) RequestNotPermitted(io.github.resilience4j.ratelimiter.RequestNotPermitted) RateLimiterOperator(io.github.resilience4j.ratelimiter.operator.RateLimiterOperator) Single(io.reactivex.Single) Flowable(io.reactivex.Flowable)

Aggregations

Flowable (io.reactivex.Flowable)65 Test (org.junit.Test)29 List (java.util.List)21 TimeUnit (java.util.concurrent.TimeUnit)19 Observable (io.reactivex.Observable)14 TestSubscriber (io.reactivex.subscribers.TestSubscriber)14 Assert.assertTrue (org.junit.Assert.assertTrue)14 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)13 Single (io.reactivex.Single)13 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)13 ClientBuilder (javax.ws.rs.client.ClientBuilder)13 MediaType (javax.ws.rs.core.MediaType)13 AbstractResourceInfo (org.apache.cxf.jaxrs.model.AbstractResourceInfo)13 FlowableRxInvoker (org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker)13 FlowableRxInvokerProvider (org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider)13 AbstractBusClientServerTestBase (org.apache.cxf.testutil.common.AbstractBusClientServerTestBase)13 BeforeClass (org.junit.BeforeClass)13 Collections (java.util.Collections)9 Response (javax.ws.rs.core.Response)9 Assert.assertEquals (org.junit.Assert.assertEquals)9