TakeWhile

镜像可观察对象发出的项目,直到指定条件变为 false

TakeWhile

The TakeWhile mirrors the source Observable until such time as some condition you specify becomes false, at which point TakeWhile stops mirroring the source Observable and terminates its own Observable.

另请参阅

特定语言信息

待定

takeWhile

The takeWhile operator returns an Observable that mirrors the behavior of the source Observable until such time as a function, applied to an item emitted by that Observable, returns false, whereupon the new Observable terminates with an onCompleted notification.

numbers = Observable.from( [1, 2, 3, 4, 5, 6, 7, 8, 9] );

numbers.takeWhile({ ((it < 6) || (0 == (it % 2))) }).subscribe(
  { println(it); },                          // onNext
  { println("Error: " + it.getMessage()); }, // onError
  { println("Sequence complete"); }          // onCompleted
);
1
2
3
4
5
6
Sequence complete

takeWhile does not by default operate on any particular Scheduler.

takeWhile

The takeWhile operator returns an Observable that mirrors the behavior of the source Observable until such time as a function, applied to an item emitted by that Observable, returns false, whereupon the new Observable terminates with an onCompleted notification.

takeWhile does not by default operate on any particular Scheduler.

takeWhile

RxJS 实现 takeWhile 运算符。你可以向它传递一个函数来控制获取过程。takeWhile 会对源可观察对象发出的每个项目调用该函数,直到该函数返回 false 为止,此时 takeWhile 会停止镜像源可观察对象(从该项目开始)并发出 onCompleted 通知。该函数接受三个参数

  1. 发出的项目
  2. 该项目在发射序列中的基于零的索引
  3. 源可观察对象

您可以选择向 takeWhile 传递第二个参数。如果是这样,该项目也会作为“this”提供给你的谓词函数。

示例代码

var source = Rx.Observable.range(1, 5)
    .takeWhile(function (x) { return x < 3; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: 0
Next: 1
Next: 2
Completed

takeWhile 存在于以下每个发行版中

  • rx.js
  • rx.all.js
  • rx.all.compat.js
  • rx.compat.js
  • rx.lite.js
  • rx.lite.compat.js

RxPHP 将此运算符实现为 takeWhile

只要指定条件为真,就返回来自可观察序列的元素。它接受一个回调作为参数,用于测试每个源元素的条件。回调谓词使用元素的值进行调用。

示例代码

//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeWhile.php


$source = \Rx\Observable::range(1, 5)
    ->takeWhile(function ($x) {
        return $x < 3;
    });

$subscription = $source->subscribe($stdoutObserver);


   
Next value: 1
Next value: 2
Complete!
    

RxPHP 还具有一个运算符 takeWhileWithIndex

只要指定条件为真,就返回来自可观察序列的元素。它接受一个回调作为参数,用于测试每个源元素的条件。回调谓词使用索引和元素的值进行调用。

示例代码

//from https://github.com/ReactiveX/RxPHP/blob/master/demo/take/takeWhileWithIndex.php


$source = \Rx\Observable::range(1, 5)
    ->takeWhileWithIndex(function ($i) {
        return $i < 3;
    });

$subscription = $source->subscribe($stdoutObserver);


   
Next value: 1
Next value: 2
Next value: 3
Complete!