Rxjava 简明教程

RxJava - Combining Operators

以下是用于从多个 Observable 中创建单个 Observable 的操作符。

Following are the operators which are used to create a single Observable from multiple Observables.

Sr.No.

Operator & Description

1

*And/Then/When*Combine item sets using Pattern and Plan intermediaries.

2

*CombineLatest*Combine the latest item emitted by each Observable via a specified function and emit resulted item.

3

*Join*Combine items emitted by two Observables if emitted during time-frame of second Observable emitted item.

4

*Merge*Combines the items emitted of Observables.

5

*StartWith*Emit a specified sequence of items before starting to emit the items from the source Observable

6

*Switch*Emits the most recent items emitted by Observables.

7

*Zip*Combines items of Observables based on function and emits the resulted items.

Combining Operator Example

在任意编辑器中使用任何您选择的语言(如 C:\>RxJava) 创建以下 Java 程序。

Create the following Java program using any editor of your choice in, say, C:\> RxJava.

ObservableTester.java

import io.reactivex.Observable;
//Using combineLatest operator to combine Observables
public class ObservableTester {
   public static void main(String[] args) {
      Integer[] numbers = { 1, 2, 3, 4, 5, 6};
      String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
      final StringBuilder result = new StringBuilder();
      Observable<String> observable1 = Observable.fromArray(letters);
      Observable<Integer> observable2 = Observable.fromArray(numbers);
      Observable.combineLatest(observable1, observable2, (a,b) -> a + b)
         .subscribe( letter -> result.append(letter));
      System.out.println(result);
   }
}

Verify the Result

按照如下方式使用 javac 编译器编译类 −

Compile the class using javac compiler as follows −

C:\RxJava>javac ObservableTester.java

现在按照如下所示运行 ObservableTester:

Now run the ObservableTester as follows −

C:\RxJava>java ObservableTester

它应该产生以下输出 −

It should produce the following output −

g1g2g3g4g5g6