Rxjs - Operators - Count

这个要写一下,因为被自己坑了.之前写分页的时候,忘记当时想法了,想用这个count的operator.
但不管怎么do啊 subscribe 啊 都不输出值,各种郁闷.
后来想了半天,找到怀疑对象. Completed

看文档吧,更详细

Rx.Observable.prototype.count([predicate], [thisArg])

Arguments

[predicate] (Function): A function to test each element for a condition. The callback is called with the following information:

  1. the value of the element
  2. the index of the element
  3. the Observable object being subscribed
    [thisArg] (Any): Object to use as this when executing predicate.

Returns

(Observable): An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.

  • count针对是的结束的流
  • count第一个参数是function 用来加count的条件,得出符合条件的总数
    • function 可以放3个参数
    • 每一个value
    • index
    • 被count的那个Observable
  • 第二个参数是,如果你第一个参数里用了this,这个参数可以代表this

看例子吧

var source = Rx.Observable.range(5, 10)
.count(function (x, i, o) {
console.log(x, i)
console.log(this);
},"mockThis");

var subscription = source.subscribe(
function (x) {
console.log('Next: ' + x.toString());
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
});
5 0
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
6 1
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
7 2
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
8 3
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
9 4
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
10 5
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
11 6
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
12 7
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
13 8
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
14 9
String {0: "m", 1: "o", 2: "c", 3: "k", 4: "T", 5: "h", 6: "i", 7: "s", length: 8, [[PrimitiveValue]]: "mockThis"}
Next: 0
tCompleted

输出了 value index 还有this

重点, 结束才会subscribe出值