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);
}
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())));
}
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);
}
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.");
}
}
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);
}
Aggregations