Menu
  • HOME
  • TAGS

Can't build project after adding RxJava to dependencies

java,android,android-gradle,rx-java

Taking into account the number of dependencies you have in your build.gradle, the most possible reason for having this error is an androids 65k methods limit. There are several ways to fix the error, which are described in the official documentation. I think the easiest way is to get rid...

RxJava: Reading multiple subscriptions and performing an action based on their results?

java,android,rx-java

If I understood correctly, the signatures of your Observables look similar to this: // verifier Observables which perform network calls Observable<Verification1> test1 = ... Observable<Verification2> test2 = ... ... // Observable to fire the transaction Observable<TransactionResult> fireTransaction = ... // represents the clicks on the "go" button of the UI...

Android RxJava joining lists

android,rx-java

I believe the operators you are looking for are concat or merge. Concat will emit the emissions from two or more Observables without interleaving them. Merge on the other hand will combine multiple observables by merging their emissions. For example: String[] numbers = {"1", "2", "3", "4"}; String[] letters =...

Batching inserts with RxJava

android,sqlite,rx-java

You can use buffer operator to accumulate objects. Example: Observable<String> stringObservable = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { for (int i = 0; i < 9; i++) { subscriber.onNext("a"); } subscriber.onCompleted(); } }); stringObservable .buffer(5) .subscribe(new Observer<List<String>>() { @Override public void onCompleted() { Log.i("rxjava", "onCompleted");...

RxAndroid ViewObservable NetworkOnMainThreadException

android,multithreading,rx-java,rx-android

I'm not an expert in Android but based on the error messages, I think you need to bounce the value between the main thread and the background thread. Usually, Android examples show you to add a subscribeOn/observeOn pair to your stream processing: Observable.just(1) .map(v -> doBackgroundWork()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(v ->...

How to implement observeLatestOn in RxJava (RxScala)?

scala,reactive-programming,rx-java

I recommend that using lift to implement this operator. Here is my solution: package object ObservableEx { implicit class ObserveLatestOn[T](val o: Observable[T]) { def observeLatestOn(scheduler: Scheduler): Observable[T] = { o.lift { (child: Subscriber[T]) => val worker = scheduler.createWorker child.add(worker) val parent = new Subscriber[T] { private val lock = new...

RxJava, OkHttp, Okio, file downloader in Android

android,rx-java,okhttp

Your code have some errors, which may explain that the expected behaviours is not what you get. Observable contract error Reactive Extensions (RxJava is an implemtation of it) is based on this contract : you can be notified multiple times on onNext then, you will notified once (or never...) on...

RxJava .subscribeOn(Schedulers.newThread()) questions

rx-java

As Vladimir mentioned, RxJava standard schedulers run work on daemon threads which terminate in your example because the main thread quits. I'd like to emphasise that they don't schedule each value on a new thread, but they schedule the stream of values for each individual subscriber on a newly created...

Infinite observable from another observable

java,rx-java

You can accomplish this with standard operators which will give you error propagation, unsubscription and backpressure for cheap: Observable<Integer> databaseQuery = Observable .just(1, 2, 3, 4) .delay(500, TimeUnit.MILLISECONDS); Observable<Integer> result = Observable .timer(1, 2, TimeUnit.SECONDS) .onBackpressureDrop() .concatMap(t -> databaseQuery); result.subscribe(System.out::println); Thread.sleep(10000); ...

StringObservable.from(InputStream).share() cause immediate MissingBackPressure

java,rx-java

The current v0.22 doesn't support backpressure properly so you should use onBackpressureBuffer to avoid the MissingBackpressureException for now. I'll see if we can release the latest code which should work. In addition, using share() can be surprising, because it does reference counting on the subscribers. You can't really subscribe all...

RxJava: How do I make a fetch-once-and-reuse Observable?

java,android,rx-java

To elaborate on David's correct answer, here's some code that illustrates the use of cache: public class Caching { public static void main(String[] args) throws IOException { Observable<String> observable = doSomethingExpensive().cache(); observable.subscribe(System.out::println); observable.subscribe(System.out::println); } private static Observable<String> doSomethingExpensive(){ return Observable.create(subscriber -> { System.out.println("Doing something expensive"); subscriber.onNext("A result"); subscriber.onCompleted();...

Is there an observable that just propagates the error without terminating itself?

java,android,rx-java

I'm not sure what your want to achieve with this setup, but generally, in order to avoid a terminal condition with PublishSubject, you should wrap your value and error into a common structure and always emit those, never any onError and onCompleted. One option is to use RxJava's own event...

RxJava retryWhen resubscribe propagation

java,android,java-8,retrofit,rx-java

It's looks like a bug in rx-java implementation. Anyway, throwing an exception from map function is a bad thing since the function is supposed to be pure (e.g. without side effects). You should use a flatMap operator in your case: services.getSomething() .flatMap(response -> { if (checkBadResponse(response)) { return Observable.<ResponseType>error(new RuntimeException("Error...

Conditional object creation within a stream in RxAndroid

rx-java,rx-android

You can use switchIfEmpty, such as return provider1.getObject() .filter(o -> o != null) .switchIfEmpty(provider2.getObject()); BTW, switchIfEmpty is added since RxJava 1.0.5. You may need to specify the RxJava version in your build script....

Fragment subscribe to Observer

android,observer-pattern,rx-java

No one is stepping forward, so I'll aggregate the comments into an answer. Cast to MyFragment: MyFragment myFragment = (MyFragment) mTabsPageAdapter.getItem(2); Change loadAndStoreDataObservable to be a Subscription Subscription loadAndStoreDataObservable = ... In OnDestroy(), unsubscribe: protected void onDestroy() { super.onDestroy(); if (loadAndStoreDataObservable != null) { loadAndStoreDataObservable.unsubscribe(); } } ...

RxAndroid: UI changes on Schedulers.io() thread

java,android,multithreading,rx-java,rx-android

AppObservable.bindFragment(this, Observable.just(0)) throw an exception as it's not called from the Main Thread This code is not called in the main thread because you observe on Schedulers.io in this code (see bellow), than latter call AppObservable.bindFragment(this, Observable.just(0)) AppObservable.bindFragment(this, Observable.just(0)) .observeOn(Schedulers.io()) .subscribe(v -> setWallpaperOnSeparateThread()); You want to perform a task in...

Elegant way to get index of filter or first with RX Java

filter,rx-java

There used to be mapWithIndex and zipWithIndex operators in RxJava, but they were removed, see here why. So you have to write some library boilerplate once: class Indexed<T> { final int index; final T value; public Indexed(T value, int index) { this.index = index; this.value = value; } @Override public...

How can I reuse a Subscriber between two Observables (RxJava)

java,rx-java,observable

A Subscriber should not be reused. It will not work because it is a Subscription and once unsubscribed it is done. Use an Observer instead if you want to reuse it. source...

mActivity from Fragment.onAttach() not retained

android,android-fragments,rx-java

Clearly this line is a problem: mTableLayout = (TableLayout) mActivity.findViewById(R.id.fragment_table_layout); This means you are casting a view that doesn't belong to that Fragment, in that Fragment. All view plumbing of a Fragment (including finding that TableLayout) should be done in Fragment.onCreateView. Later you can use their references elsewhere in the...

Flatten Observable> to Observable

android,rx-java,rx-android

Is there a better way to flatten Observable<Observable<Cursor>> to Observable<Cursor>? Yes, you can use Observable.concat method: public static void main(String[] args) { final Observable<String> observable = Observable.just("1", "2"); final Observable<Observable<String>> nested = observable.map(value -> Observable.just(value + "1", value + "2")); final Observable<String> flattened = Observable.concat(nested); flattened.subscribe(System.out::println); } UPDATE There...

Observable/Subscriber in AsyncTask

android,rx-java,observable

Actually RxJava is supposed to replace AsycTask. In fact I can say with confidence that AsyncTask is a subset of RxJava. In RxJava, a Subscriber would be analogous to AsyncTask.progressUpdate or onPostExecute and Observable to the process in doInBackground. Data are emitted from Observable to Subscriber and any alteration in...

LifecycleObservable for click event in background

java,android,rx-java,rx-android

Okay I think I got it: subscription = LifecycleObservable.bindActivityLifecycle(lifecycle(), AppObservable.bindActivity(this, ViewObservable.clicks(button)) .observeOn(Schedulers.computation()) .map(new Func1<OnClickEvent, String>() { @Override public String call(OnClickEvent onClickEvent) { Log.i(TAG, "1 " + Thread.currentThread()); return ((Button) onClickEvent.view()).getText().toString(); } }) .map(new Func1<String, String>() { @Override public String call(String o) { Log.i(TAG, "2 " + Thread.currentThread()); return "hallo "...

RxJava: “java.lang.IllegalStateException: Only one subscriber allowed!”

java,android,rx-java

In RxJava, the operators groupBy and window return an observable which can be subscribed to only once and if subscribed, they replay their accumulated contents to the sole subscriber and switch to 'hot' mode. This was a tradeoff between returning a fully hot observable and risk missing values or return...

Add RxJava Observer into chain depending on a condition

java,android,rx-java

Assuming the API is non-RxJava based, you can do something like this: Observable.just(1) .map(v -> { if (api.isVip()) { if (api.pendingCancel()) { return 1; } return 2; } return 3; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(v -> { if (v == 1) { YourVipIsAboutToCancelActivity.start(); } else if (v == 2) { CancelVipActivity.start();...

RxJava: difference between doOnNext and doOnEach

java,rx-java

They are indeed quite close. One thing that differs (and it's maybe not that clear in the javadoc actually, more visible in sourcecode) is that in doOnEach, you also get Notification wrappers for errors and completion event. You can then check isOnNext, isOnCompleted or isOnError to check the actual kind...

Custom Observable stream of REST results from a list of links

rx-java

When creating an Observable from a list, am I supposed to iterate over the list myself, or is there some other, better way? For instance, there is Observable.from(Iterable), but I don't think I can use it? Instead of iterating in the create method, you may build an observable per...

How can i use sqlbrite and RxJava 1.x in eclipse?

eclipse,gradle,rx-java,sqlbrite

Variants: Clone and build jars yourself -> attach to the project. Go to maven central and download jars: RxJava, SqlBrite. Switch to Gradle + Android Studio or use Maven/Ivy in Eclipse or other IDE. ...

RxJava onErrorResumeNext scheduler

java,android,rx-java

You can accomplish this by flatMapping a PublishSubject which is then updated once the relevant button is pressed. Here is a classical Java Swing example. public class RetryWhenEnter { public static void main(String[] args) { AtomicInteger d = new AtomicInteger(); Observable<Integer> source = Observable.just(1); source.flatMap(v -> { if (d.incrementAndGet() <...

RxJava - How to keep observing an object until onError() / unsubscribing

java,asynchronous,reactive-programming,rx-java,observable

This is a typical case for PublishSubject: class MyList<T> { final PublishSubject<T> onAdded = PublishSubject.create(); void add(T value) { // add internally onAdded.onNext(value); } Observable<T> onAdded() { return onAdded; } } MyList<Integer> list = populate(); Subscription s = list.onAdded() .subscribe(v -> System.out.println("Added: " + v)); list.add(1); // prints "Added: 1"...

Implement retryWhen logic

android,session,retrofit,rx-java

Use OkHttp's extremely powerful Interceptor. public class RecoverInterceptor implements Interceptor { String getAuth() { // check if we have auth, if not, authorize return "Bearer ..."; } void clearAuth() { // clear everything } @Override public Response intercept(Chain chain) throws IOException { final Request request = chain.request(); if (request.urlString().startsWith("MY ENDPOINT"))...

Writing with a single thread LMAX

java,multithreading,rx-java,disruptor-pattern,lmax

The impact on a RingBuffer of multi-treaded writing is slight but under very heavy loads can be significant. A RingBuffer implementation holds a next node where the next addition will be made. If only one thread is writing to the ring the process will always complete in the minimum time,...

RxJava: Find out if BehaviorSubject was a repeated value or not

java,android,reactive-programming,rx-java

As you mentioned in the question, this can be accomplished with multiple Observables. In essence, you have two Observables: "the fresh response can be observed", and "the cached response can be observed". If something can be "observed", you can express it as an Observable. Let's name the first one original...

HashMaps vs Reactive Programming

java,monads,reactive-programming,rx-java

Using BehaviorSubject is the right thing to do here if you don't care about earlier values. Note most post discouraging Subjects were written in the early days of Rx.NET and is mostly quoted over and over again without much thought. I attribute this to the possibility that such authors didn't...

Observable.interval() with initialDelay

android,rx-java

RxJava has 3 timing related operators (+1 overload each): timer(long delay, TimeUnit unit [, Scheduler scheduler]) emits a single 0L after the delay, timer(long initialDelay, long period, TimeUnit unit [, Scheduler scheduler]) emits a 0L after the initial delay and ever incrementing values periodically after that, interval(long interval, TimeUnit unit...

How do I extract the last value from an Observable and return it?

java,reactive-programming,rx-java

Here is one way to do this, essentially by creating a BlockingObservable. This is flaky though as it has the potential to hang if the underlying observable does not complete: observableLocation.toBlocking().last() ...

Error handling for zipped observables

rx-java

First of all, the right way to notify a Subscriber about an error is to call subscriber.onError method: class SubscribingRestCallback implements RestCallback { private final Subscriber<? super Content> subscriber; public SubscribingRestCallback(Subscriber<? super Content> subscriber) { this.subscriber = subscriber; } @Override public void onSuccess(Content content) { subscriber.onNext(content); subscriber.onCompleted(); } @Override public...

How wait observable result from independent components in rxjava

reactive-programming,rx-java

You can call cache() on the returned Observable in getSessionFromInternetOrCache and it will make sure the session will be retrieved only once and replayed to anyone trying to observe it later. I assume the actual session retrieval only happens when one subscribes to the Observable. Edit: this example shows what...

Using RxJava to process varying object stream

rx-java

Here is an example how it could be done by using RxJava: public class MultikindSource { enum ValueType { TIMESTAMP, NUMBER, FOO } static final class Foo { } static Observable<Object> source(String timestamp) { return Observable.from(Arrays.asList(timestamp, new Foo(), new Foo(), 1, 2, 3, new Foo())); } public static void main(String[]...

One observable two observers

rx-java

For the sake of completeness: PublishSubject can transmit events to more than one subscribers.

How to use RxJava for file parsing and SQL generation?

java,multithreading,system.reactive,rx-java,rx-android

Rx (on any platform) is not well suited for most forms of parallel processing. It deals with streams, which are inherently serialized. It sounds like you are looking for some kind of ETL tool.

RxJava- performing a peek() or void operation within an Observable chain?

java,reactive-programming,rx-java

There is a method doOnNext(Action1<Item> action) that will be called for each item in the stream. Documentation...

How can I create an Observer over a dynamic list in RxJava?

rx-java

There you go. Thanks to Dávid Karnok on RxJava Google Group import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.subjects.PublishSubject; public class ObservableListExample { public static class ObservableList<T> { protected final List<T> list; protected final PublishSubject<T> onAdd; public ObservableList() { this.list = new ArrayList<T>(); this.onAdd = PublishSubject.create(); } public void add(T...

At what point in the View lifecycle should I unsubscribe if the View is never made visible?

android,android-view,rx-java,rx-android

A graphical element like a view should not be performing any logic that doesn't directly effect drawing. It should not be localizing text, instead localized text should be passed in to it.

How to convert callback based API into one based on Observable?

java,multithreading,rx-java

I think you need something like this (example given in scala) import rx.lang.scala.{Observable, Subscriber} case class Message(message: String) trait MessageCallback { def onMessage(message: Message) } object LibraryObject { def setCallback(callback: MessageCallback): Unit = { ??? } def removeCallback(callback: MessageCallback): Unit = { ??? } def start(): Unit = { ???...

Giving an RxJava Observable something to emit from another method

java,android,rx-java

RxJava has Subjects for this purpose. For example: private final PublishSubject<String> subject = PublishSubject.create(); public Observable<String> getUiElementAsObservable() { return subject; } public void updateUiElementValue(final String value) { subject.onNext(value); } ...

Delay items emission until item is emitted from another observable

reactive-programming,rx-java

AFAIK, there is no a built-in operator to achieve the behavior you've described. You can always implement a custom operator or build it on top of existing operators. I think the second option is easier to implement and here is the code: public static <L, R, T> Observable<T> zipper(final Observable<?...

How to bind Radio Buttons using RxJava

android,rx-java,radio-group,rx-android

I was able to solve this on my own. Here's the answer for anyone who might come across the same issue.... I wrote a function in the class as protected RxAction<RadioGroup, String> setRadioButton() { return new RxAction<RadioGroup, String>() { @Override public void call(final RadioGroup radioGroup, final String selection) { RadioButton...

Observable's doOnError correct location

java,rx-java

Yes, it does. doOnError acts when an error is passing through the stream at that specific point, so if the operator(s) before doOnError throw(s), your action will be called. However, if you place the doOnError further up, it may or may not be called depending on what downstream operators are...

RXJava - Split and Combine an Observable

android,system.reactive,rx-java

Here is an example with groupBy: public class Multikind2 { static Observable<Object> getSource() { return Observable.just("String", Arrays.asList(1, 2, 3, 4)); } enum ValueKind { STRING, LIST } public static void main(String[] args) { Func1<Object, ValueKind> kindSelector = o -> { if (o instanceof String) { return ValueKind.STRING; } else if...

How cancel task with retrofit and rxjava

retrofit,reactive-programming,rx-java,okhttp

You can use the standard RxJava cancelling mechanism Subscription. Observable<String> o = retrofit.getObservable(..); Subscription s = o.subscribe(...); // later when not needed s.unsubscribe(); Retrofit RxJava connector will redirect this call to okHttp's cancel. See here: https://github.com/square/retrofit/blob/master/retrofit-adapters/rxjava/src/main/java/retrofit/ObservableCallAdapterFactory.java#L92...

Use RxJava and Retrofit to iterate through list and augment results based on subqueries

android,retrofit,rx-java,retrolambda

You could insert doOnNext at certain points of the stream to add side-effects: apiService.getWidgets(token) .flatMapIterable(v -> v) .flatMap(w -> apiService.getArticles(token, w.type) .flatMapIterable(a -> a) .doOnNext(a -> db.insert(a)) .doOnNext(a -> { w.articleName = a.name; w.articleUrl = a.url; }) .takeLast(1) .map(a -> w) ) .toList() .subscribe( modifiedWidgets -> saveWidgets(modifiedWidgets), throwable -> processWidgetError(throwable)...

How use multiple observable's results in subscriber

reactive-programming,rx-java

Instead of building an Observable<Integer>, build an Observable<MyPair>. MyPair will be a class that will keep the hashcode and your object. class MyPair<T> { private final int hashCode; private final T value; } Observable.just("Moscou").map(city -> new MyPair<String>(city, city.hashCode()).subscribe(pair -> /** **/); ...

How to get BehaviorSubject-like behavior from a filtered Observable?

rx-java

You can use compose to chain them, such as: public class BehaviorSubjectTransformer<T> implements Observable.Transformer<T, T> { @Override public Observable<T> call(Observable<T> o) { BehaviorSubject<T> subject = BehaviorSubject.create(); o.subscribe(subject); return subject; } public static <T> Observable.Transformer<T, T> create() { return new BehaviorSubjectTransformer<T>(); } } @Test public void foo() { Observable<Integer> o =...

How to return value with RxJava?

android,rx-java

You need a better understanding of RxJava first, what the Observable -> push model is. This is the solution for reference: public class Foo { public static Observable<File> getMeThatThing(final String id) { return Observable.create(subscriber => { try { File file = getFile(id); subscriber.onNext(file); if (!subscriber.isUnsubscribed()){ subscriber.onComplete(); } } catch (WhateverException...

rxjava add items after observable was created

asynchronous,observable,rx-java,rx-android

What you probably need is Subject - http://reactivex.io/documentation/subject.html It is an object that is both Observer and Observable, hence you can subscribe to it and emit new items. For example : PublishSubject<String> subject = PublishSubject.create(); subject.subscribe(System.out::println); subject.onNext("Item1"); subject.onNext("Item2"); ...

RxJava and Retrofit - Raising custom exceptions depending on server response

android,retrofit,rx-java

I would like to raise an exception for subscribers if code is anything other than 0. How is it possible using Retrofit and Rx? You can use a Observable.flatMap operator: api.request().flatMap(response -> { if (response.getCode() != 0) { return Observable.error(new Exception("Remote error occurred")); } return Observable.just(response); }); I would...

Subscribe on RxJava observable multiple times

java,reactive-programming,rx-java,observable

Your whole flow of events is wrong, you should be updating the UI in subscriber, not in doOnNext. API.getVideoListObservable() .map(r -> r.getObjects()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(videos -> { // do stuff with videos fragment.updateVideoList(videos); kalturaVideoList.addAll(videos); }, throwable -> { // handle errors throwable.printStackTrace(); }); Retrofit sets subscribeOn(Schedulers.io()) for you. Move everything into...

How to aggregate multiple JavaRX Observables

java,rx-java

I think you need mergeDelayError. It merges multiple Observables, the same as merge, but its JavaDoc says - Flattens N Observables into one Observable, in a way that allows an Observer to receive all successfully emitted items from all of the source Observables without being interrupted by an error notification...

Relationship between rxJava and promises

java,promise,rx-java

As the comment explain, a promise will allow you to chain operation, but in the end, you'll get one result. With RxJava, you can be notified multiple time and then get multiple result. Promise can be seen as async operation, and Observable as async* operation. ...

Deliver the first item immediately, 'debounce' following items

rx-java,rx-android

Update: From @lopar's comments a better way would be: Observable.from(items).publish(publishedItems -> publishedItems.limit(1).concatWith(publishedItems.skip(1).debounce(1, TimeUnit.SECONDS))) Would something like this work: String[] items = {"one", "two", "three", "four", "five", "six", "seven", "eight"}; Observable<String> myObservable = Observable.from(items); Observable.concat(myObservable.first(), myObservable.skip(1).debounce(1, TimeUnit.SECONDS)) .subscribe(s -> System.out.println(s)); ...

How do I recurse in RxJava while only using a single thread?

java,multithreading,recursion,reactive-programming,rx-java

I've tried to make an analogue to your code by recursively listing a local directory and I don't experience any hangs. My guess is that your single connection enforced by the server, the recursive call tries to establish a new connection before the previous is terminated. I'd move urlConnection.disconnect(); before...

How to get latest value from BehaviorSubject?

java,android,reactive-programming,rx-java,rx-android

As it turns out, the reason behind it is that RxAndroid by default depends on RxJava 1.0.4, where Subjects didn't expose getValue nor hasValue yet. Thanks to @akarnokd for helping me realize that. As it turns out, all it takes to resolve the problem is to manually add a dependency...

Adapter Subscribing to Multiple Observables

android,android-sqlite,baseadapter,rx-java,sqlbrite

You should avoid using the same adapter for two different stream, as it will have to deal concurrent issue, that you can avoid using RxJava. Why not try to merge your streams into a single one, and, then, use only one adapter ? TrackerDbUtils.getListSubmissionObservable(db) .map(Submission.MAP) .mergeWith(TrackerDbUtils.getSummaryObservable(db) .map(Summary.MAP)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mAdapter);...

RxJava asynchronous observer misses elements

rx-java

Threads underlying RxJava schedulers are all daemon threads and they are stopped by the JVM if all other non-daemon threads have completed. If you run your examples from static void main(), it is very likely your main() method will terminate before the other threads had a chance of running and...

Timer RXjava: control system function

rx-java

What about this: averageTempStream.map((Double v) -> { // check whether the value is ok (v > averageTempSensors - threshold) && (v < averageTempSensors + threshold) }) .distinctUntilChanged() // ignore subsequent identical values // (e. g. "x-x-x-x-a-a-x" becomes "x- - - -a- -x") .debounce(t, TimeUnit.SECONDS) // only emit a value if...

RxJava alternative for map() operator to save emitted items

android,retrofit,rx-java

Following Egor's answer I did some research and, based on Dan Lew's blogpost and this question, the correct answer appears to be doOnNext.

Why is my RxJava observable not firing off subscribers?

java,multithreading,asynchronous,reactive-programming,rx-java

You are starting the processing pipeline using Schedules.computation which runs daemon threads. Thus when your main thread finishes, those threads are terminated before processing your observable. So if you would like to see your results printed you could have your main thread wait for the results (e.g. by Thread.sleep) or...

How to create an Observable from an Observable>

java,rx-java,observable

Use flatMapIterable. For example: observable.flatMapIterable(l -> l).subscribe() ...

How to transform a nested list of double values into a Java class using RxJava?

android,retrofit,rx-java,observable,rx-android

According to your Data, you receive a list of pair (timestamp, level). This pair is represented by a list which contains only 2 values. So you want to emit each pair, and transform each pair into a ProductLevel. To do this, you'll have to flatMap your list of pair to...

How can i change a Field in a List of Objects with RXJava/Android

android,rx-java,observable

List<Person> personList = new ArrayList<Person>(); // populate personList Observable.from(personList).forEach((person)-> { person.setName(name); person.setCity(city); }); alternate version: List<Person> personList = new ArrayList<Person>(); // populate personList Observable.from(personList).forEach((person)-> p.fillPersonData() ); Alternate version: List<Person> personList = new ArrayList<Person>(); // populate personList Observable<Person> observable = Observable.from(personList)...

Best practices for exposing “expensive” Observables in RxJava

rx-java

Your example class can't really work: setBar can throw NPE if subscriber is null, the runUntilUnsubscribed references a missing bar field/value and is a busy loop that would emit the same value over and over. You say creating a Bar is expensive, but its creation seems to be outside the...

Difference between Java 8 streams and RxJava observables

java-8,java-stream,rx-java,observable

Java 8 Stream and RxJava looks pretty similar. They have look alike operators (filter, map, flatMap...) but are not built for the same usage. You can perform asynchonus tasks using RxJava. With Java 8 stream, you'll traverse items of your collection. You can do pretty much the same thing in...

RxJava: what is difference between callbacks in doOnError('callback') and subscribe(*, 'callback')

java,reactive-programming,rx-java

The doOnError operator allows you to inject side-effect into the error propagation of a sequence, but does not stop the error propagation itself. The Subscriber is the final destination of the events and they 'exit' the sequence. You can see the usefulness of doOnError with the following example: api.getData() .doOnError(e...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java

I think, your case can be accomplished with a combination of merge, filter and take: List<Observable<HotelInfo>> hotels = new ArrayList<>(); for (URL u : urls) { Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u); hotels.add(hotelInfo); } Observable.merge(hotels) .filter(h -> h.vacancy > 0) .take(1) .subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace); ...

How do I chain execution two indepentent Observables serially without nesting the calls?

java,rx-java

You should use flatMap: obsOfA.flatMap(new Func1<A, Observable<B>>() { @Override public Observable<B> call(A a) { return obsOfB; } }) .subscribe(/* obsOfB has completed */); Every time obsOfA calls onNext(a), call will be executed with this value a....

How to ignore error and continue infinite stream?

android,rx-java,rx-android

There is no out of the box solution but this may be of some help to you https://groups.google.com/forum/#!topic/rxjava/trm2n6S4FSc...

Asynchronously Publish to Observable/Subject

rx-java,rx-android

Observable.from(listOfObjects) will create a new observable that will emit each of list's objects. You can write Observable.just(1, 2, 3, 4) too. It's the same thing. So, if you add an object into your list, the Observable won't be notified. You can create a custom list that will notify your Observable...

Does a single Observable notify sequentially to all its Observers?

java,rx-java

want to understand why the notification is blocking The implementation of RxJava assumes that executing the onNext method of an Observer is always fast and cheap, so PublishSubject just calls all onNext methods of its Observers one after the other, without introducing any concurrency. as well and how can...

Does rxjava with couchbase offer value for non-bulk opertions

java,couchbase,reactive-programming,rx-java

For an operation on a single document where ultimately you need to block, I'd tend to agree that your second example is clearer. RxJava shines when you heavily use asynchronous processing, especially when you need advanced error handling, retry scenarii, combination of asynchronous flows... The previous generation of Couchbase Java...

RxJava observables not emitting events

android,retrofit,reactive-programming,rx-java,observable

mFeedInfoObservable = Observable.empty(); You build an empty Observable that will never emit value. So when you'll subscribe to this Observable, you'll be only notified of it's completion. mFeedInfoObservable.mergeWith(Observable.just(feedInfo)); Observable are immutable. It's mean that calling a method won't change its state. mergeWith will produce a new Observable that is...

RxJava: How to interrupt thread on unsubscribe?

rx-java,cancellation

When you call yourSubscription.unsubscribe();, Rx will call your unsubscribe code. This unsuscribe code will be the Subscription class that you can add to your subscriber when you create your Observable. Observable<Object> obs = Observable.create(subscriber -> { subscriber.add(new Subscription() { @Override public void unsubscribe() { // perform unsubscription } @Override public...

Transform RxJava observable's error into another observable and swallow success

retrofit,reactive-programming,rx-java,observable

You should call a userService.register from onErrorResumeNext The easiest way to distinguish what kind of error happened is to introduce a separate Exception class for each error. This is how it looks in code: userService.checkLogin(mPhone).flatMap(new Func1<Response, Observable<Response>() { @Override public Observable<? extends Response> call(final Response response) { // according...

Split Rx Observable into multiple streams and process individually

reactive-programming,rx-java,rxjs

You don't have to collapse Observables from groupBy. You can instead subscribe to them. Something like this: String[] inputs= {"a", "b", "c", "a", "b", "b", "b", "a"}; Action1<String> a = s -> System.out.print("-a-"); Action1<String> b = s -> System.out.print("-b-"); Action1<String> c = s -> System.out.print("-c-"); Observable .from(inputs) .groupBy(s -> s)...

RxJava - Just vs From

rx-java

The difference should be clearer when you look at the behaviour of each when you pass it an Iterable (for example a List): Observable.just(someList) will give you 1 emission - a List. Observable.from(someList) will give you N emissions - each item in the list. The ability to pass multiple values...

Using ReactFX to resize stage when nodes become invisible?

javafx,javafx-8,rx-java,reactfx

I will assume that the child list of your gridPane is fixed, since in your code you just iterate through it once. First, why not bind managedProperty of each child to its visibleProperty? gridPane.getChildren().stream().forEach(c -> { c.managedProperty().bind(c.visibleProperty()); }); To get notified when any child changes its visibility, you can construct...

RxJava zip with vararg observables

java,reactive-programming,rx-java

There is a zip method which takes an Iterable. That would allow to use n Observables.

Can RxJava reduce() be unsafe when parallelized?

java,multithreading,reactive-programming,rx-java

The problem lies in the shared state between realizations of the chain. This is pitfall # 8 in my blog: Shared state in an Observable chain Let's assume you are dissatisfied with the performance or the type of the List the toList() operator returns and you want to roll your...

Spark,Akka,Storm Or RxJava [closed]

apache-spark,akka,storm,rx-java,spark-streaming

Based on my experience I would go for Akka. You can create different pools of actors to perform some tasks concurrently on different messages. Also you can leverage the power of akka-camel to have a RabbitMQ consumer using the RabbitMQ Camel Component. You might be able to do the same...

How cancel network request in retrofit and rxjava

retrofit,reactive-programming,rx-java

You can have a common SerialSubscription and assign your subscriber to it on button click. It will unsubscribe and thus cancel your previous stream: SerialSubscription serial = new SerialSubscription(); for (Button btn : buttons) { btn.setOnClickListener(e -> { Subscriber<JsonElement> s = new Subscriber<JsonElement>() { @Override public void onCompleted() {} @Override...

How to structure my app using MVP with rxjava and retrofit to get data out of Observables?

android,retrofit,rx-java

I have also started to learn something similar. Here, I would rather use callbacks. In your presenter, public void setList(List<User> users) { yourView.setUserList(users); } And your activity which implements a view (MVP) @Override public void setUserList(List<User> users) { ((UserAdapter)mGridView.getAdapter()).refill(mFriends); } Also, check that retrofit is not returning null list. I...