Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use zip() instead of zipWith() RxJava

Tags:

java

rx-java

Is there any semantic difference in pairwise composing with zip() vs. zipWith() in RxJava? Is the choice between the static zip and the .zipWith purely stylistic?

like image 868
Stuckzilla Avatar asked Aug 08 '17 18:08

Stuckzilla


People also ask

What is zip in RxJava?

RxJava Parallelization Concurrency : Zip() Operator Zip operator is used to combine emission from multiple observable into a single observable. Marble Diagram for Zip Operator. Zip Operator Works in Sequence. That means each observable will be executed sequentially.

Is RxJava deprecated?

RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.

What is single RxJava?

Single. Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response. Sample Implementation: The below code always emits a Single user object.

What is RxJava used for?

RxJava is a Java library that enables Functional Reactive Programming in Android development. It raises the level of abstraction around threading in order to simplify the implementation of complex concurrent behavior.


1 Answers

Convenience and context.

The static zip is useful when you have two sources already assembled and now you want to zip them together. Most of the time they are themselves long chains or come from all over the place.

Observable<T1> source1 = op().op().op().op().op();
Observable<T2> source2 = op().op().op().op().op();

Observable.zip(source1, source2, (a, b) -> a + b);

The instance zipWith is useful when one of the sources is longer while the other is shorter. At that point, it is more convenient to zip with the shorter one.

public Observable<R> withIndex(Observable<T> source, Func2<Integer, T, R> func) {
    return source.zipWith(Observable.range(0, Integer.MAX_VALUE),
         (t, idx) -> func(idx, t));
}
like image 142
akarnokd Avatar answered Sep 19 '22 18:09

akarnokd