官术网_书友最值得收藏!

  • Learning RxJava
  • Thomas Nield
  • 277字
  • 2021-07-02 22:22:57

takeWhile() and skipWhile()

Another variant of the take() operator is the takeWhile() operator, which takes emissions while a condition derived from each emission is true. The following example will keep taking emissions while emissions are less than 5. The moment it encounters one that is not, it will call the onComplete() function and dispose of this:

import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {

Observable.range(1,100)
.takeWhile(i -> i < 5)
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}

The output of the preceding code snippet is as follows:

RECEIVED: 1
RECEIVED: 2
RECEIVED: 3
RECEIVED: 4

Just like the takeWhile() function, there is a skipWhile() function. It will keep skipping emissions while they qualify with a condition. The moment that condition no longer qualifies, the emissions will start going through. In the following code, we skip emissions as long as they are less than or equal to 95. The moment an emission is encountered that does not meet this condition, it will allow all subsequent emissions going forward:

import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {

Observable.range(1,100)
.skipWhile(i -> i <= 95)
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}

The output of the preceding code snippet is as follows:

RECEIVED: 96
RECEIVED: 97
RECEIVED: 98
RECEIVED: 99
RECEIVED: 100
The takeUntil() operator is similar to  takeWhile(), but it accepts another  Observable as a parameter. It will keep taking emissions until that other  Observable pushes an emission. The  skipUntil()  operator has similar behavior. It also accepts another  Observable as an argument but it will keep skipping until the other  Observable emits something. 
主站蜘蛛池模板: 武胜县| 抚州市| 遂昌县| 新源县| 贵定县| 胶南市| 瑞金市| 兴和县| 通海县| 雅安市| 上蔡县| 和平县| 宣城市| 西青区| 从化市| 济宁市| 德令哈市| 洛宁县| 黎城县| 晴隆县| 积石山| 友谊县| 荔浦县| 怀宁县| 香河县| 兰西县| 涟水县| 河津市| 余江县| 黑龙江省| 璧山县| 东丰县| 永丰县| 南安市| 常德市| 平安县| 东乡| 龙泉市| 九台市| 闻喜县| 雷山县|