Christian-health / StudyNote2017

2017年学习笔记
0 stars 0 forks source link

RxJs ------- A #11

Open Christian-health opened 6 years ago

Christian-health commented 6 years ago

Aggregate (reduce)

apply a function to each item emitted by an Observable, sequentially, and emit the final value 对Observable发出的每个项目顺序应用一个函数,并发出最终的值

image

The Reduce operator applies a function to the first item emitted by the source Observable and then feeds the result of the function back into the function along with the second item emitted by the source Observable, continuing this process until the source Observable emits its final item and completes, whereupon the Observable returned from Reduce emits the final value returned from the function. Reduce操作符对源Observable发出的第一个项目应用一个函数,然后将该函数的结果与源Observable发出的第二个项目一起反馈到该函数中,继续此过程,直到源Observable发出其最终项目, 完成,然后从Reduce返回的Observable发出从函数返回的最终值。

This sort of operation is sometimes called “accumulate,” “aggregate,” “compress,” “fold,” or “inject” in other contexts. 这种操作有时在其他上下文中被称为“累加”,“聚合”,“压缩”,“折叠”或“注入”。

image

RxJS implements the reduce operator. Pass it an accumulator function, and, optionally, a seed value to pass into the accumulator function with the first item emitted by the source Observable. RxJS实现了reduce操作符。 传递一个累加器函数,以及可选的种子值,以便通过源Observable发出的第一个项目传入累加器函数。

var source = Rx.Observable.range(1, 3)
    .reduce(function (acc, x) {
        return acc * x;
    }, 1)

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: 6
Completed
Christian-health commented 6 years ago

All / every / jortSort / jortSortUntil

determine whether all items emitted by an Observable meet some criteria 确定Observable发出的所有项目是否符合某些标准 image

Pass a predicate function to the All operator that accepts an item emitted by the source Observable and returns a boolean value based on an evaluation of that item. All returns an Observable that emits a single boolean value: true if and only if the source Observable terminates normally and every item emitted by the source Observable evaluated as true according to this predicate; false if any item emitted by the source Observable evaluates as false according to this predicate.

将一个谓词函数传递给接受Source Observable发出的一个项目的All运算符,并根据该项目的评估返回一个布尔值。 全部返回一个可发出单个布尔值的Observable:当且仅当源Observable正常终止且源Observable发出的每个项目根据该谓词计算为true时为true。 如果源Observable发出的任何项目根据该谓词计算为false,则为false。

image

var source = Rx.Observable.of(1,2,3,4,5)
  .every(function (x) {
    return x < 6;
  });

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
Next: true
Completed

There is also a jortSort operator that performs a test on the entire sequence of items emitted by the source Observable. If those items are emitted in sorted order, upon the successful completion of the source Observable, the Observable returned from jortSort will emit true and then complete. If any of the items emitted by the source Observable is out of sort order, upon the successful completion of the source Observable, the Observable returned from jortSort will emit false and then complete. 还有一个jortSort操作符,对源Observable发出的整个项目序列进行测试。 如果这些项目按排序顺序排列,则在成功完成源Observable后,从jortSort返回的Observable将会发出true,然后完成。 如果源Observable发出的任何项目不符合排序顺序,则在成功完成源Observable后,从jortSort返回的Observable将发出false并完成。 There is also a jortSortUntil operator. It does not wait until the source Observable completes to evaluate its sequence for sortedness, as jortSort does, but waits until a second Observable emits an item to do so.

var source = Rx.Observable.of(1,2,3,4) // already sorted
               .jortSort();

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
Next: true
Completed
var source = Rx.Observable.of(3,1,2,4) // not sorted
               .jortSort();

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
Next: false
Completed
var just = Rx.helpers.just;

var source = Rx.Observable.of(1,2,3,4) // already sorted          //这段代码根本直接跑不起来,没看懂
               .flatmap(function (x) {
                 return Rx.Observable.timer(1000).map(just(x));
               }).jortSortUntil(Rx.Observable.timer(3000);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
Next: true
Completed
var just = Rx.helpers.just; //这段代码根本直接跑不起来,没看懂

var source = Rx.Observable.of(3,1,2,4) // not sorted
               .flatmap(function (x) {
                 return Rx.Observable.timer(1000).map(just(x));
               }).jortSortUntil(Rx.Observable.timer(3000);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (e) { console.log('Error: %s', e); },
  function ( ) { console.log('Completed'); });
Next: false
Completed
Christian-health commented 6 years ago

Amb ($q.race) /ambArray / ambWith

ambArray / ambWith打开页面之后还是amb

given two or more source Observables, emit all of the items from only the first of these Observables to emit an item or notification 从两个或者更多个Observable中,选择出第一个开始向往发射item的Observable然后,把这个Observable的所有东西全部输出。

image

When you pass a number of source Observables to Amb, it will pass through the emissions and notifications of exactly one of these Observables: the first one that sends a notification to Amb, either by emitting an item or sending an onError or onCompleted notification. Amb will ignore and discard the emissions and notifications of all of the other source Observables. 当你传递多个Observable到Amb中的时候,它将通过这些Observables中的一个的排放和通知: amb会读取并使用第一个发出item的Observable或者说,不是发出一个正常的item,onError,或者onCompleted也可以。

image RxJS implements this operator as amb. It takes a variable number of parameters, which may be either Observables or Promises (or combinations of the two). RxJS将此运算符实现为amb。 它需要可变数量的参数,它们可以是Observables或Promises(或两者的组合)。

/* Using Observable sequences */
var source = Rx.Observable.amb(
    Rx.Observable.timer(500).select(function () { return 'foo'; }),// 延迟500毫秒
    Rx.Observable.timer(200).select(function () { return 'bar'; })//延迟200毫秒
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: bar
Completed
/* Using Promises and Observables */
var source = Rx.Observable.amb(
    RSVP.Promise.resolve('foo')
    Rx.Observable.timer(200).select(function () { return 'bar'; })
//select (alternate name of Filter)  ,select操作符的别名是Filter
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: foo
Completed
Christian-health commented 6 years ago

And/Then/When

combine sets of items emitted by two or more Observables by means of Pattern and Plan intermediaries 合并2个或者多个Observable发出的item集和,通过使用Pattern(模式)和Plan intermediaries(计划中间机构)

这翻译真狗血

image

The combination of the And, Then, and When operators behave much like the Zip operator, but they do so by means of intermediate data structures. And accepts two or more Observables and combines the emissions from each, one set at a time, into Pattern objects. Then operates on such Pattern objects, transforming them in a Plan. When in turn transforms these various Plan objects into emissions from an Observable.

And,Then和When操作符的组合与Zip操作符非常相似,但是它们通过中间数据结构来实现。 并接受两个或更多的可观测量,并将每次发射,一次一组的发射组合到Pattern对象中。 然后对这样的Pattern对象进行操作,在Plan中进行转换。 反过来,将这些各种计划对象转换为可观察的排放。

http://www.introtorx.com/content/v1.0.10621.0/12_CombiningSequences.html#AndThenWhen 这个页面上有详细的关于AndThenWhen的解释。

在RxJs官网上的see also可以看到这个东西。 image

If Zip only taking two sequences as an input is a problem, then you can use a combination of the three And/Then/When methods. These methods are used slightly differently from most of the other Rx methods. Out of these three, And is the only extension method to IObservable. Unlike most Rx operators, it does not return a sequence; instead, it returns the mysterious type Pattern<T1, T2>. The Pattern<T1, T2> type is public (obviously), but all of its properties are internal. The only two (useful) things you can do with a Pattern<T1, T2> are invoking its And or Then methods. The And method called on the Pattern<T1, T2> returns a Pattern<T1, T2, T3>. On that type, you will also find the And and Then methods. The generic Pattern types are there to allow you to chain multiple And methods together, each one extending the generic type parameter list by one. You then bring them all together with the Then method overloads. The Then methods return you a Plan type. Finally, you pass this Plan to the Observable.When method in order to create your sequence.

It may sound very complex, but comparing some code samples should make it easier to understand. It will also allow you to see which style you prefer to use.

To Zip three sequences together, you can either use Zip methods chained together like this:

var one = Observable.Interval(TimeSpan.FromSeconds(1)).Take(5);
var two = Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(10);
var three = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(14);
//lhs represents 'Left Hand Side'
//rhs represents 'Right Hand Side'
var zippedSequence = one
.Zip(two, (lhs, rhs) => new {One = lhs, Two = rhs})
.Zip(three, (lhs, rhs) => new {One = lhs.One, Two = lhs.Two, Three = rhs});
zippedSequence.Subscribe(
Console.WriteLine,
() => Console.WriteLine("Completed"));

Or perhaps use the nicer syntax of the And/Then/When:

var pattern = one.And(two).And(three);
var plan = pattern.Then((first, second, third)=>new{One=first, Two=second, Three=third});
var zippedSequence = Observable.When(plan);
zippedSequence.Subscribe(
Console.WriteLine,
() => Console.WriteLine("Completed"));

This can be further reduced, if you prefer, to:

var zippedSequence = Observable.When(
one.And(two)
.And(three)
.Then((first, second, third) => 
new { 
One = first, 
Two = second, 
Three = third 
})
);
zippedSequence.Subscribe(
Console.WriteLine,
() => Console.WriteLine("Completed"));

The And/Then/When trio has more overloads that enable you to group an even greater number of sequences. They also allow you to provide more than one 'plan' (the output of the Then method). This gives you the Merge feature but on the collection of 'plans'. I would suggest playing around with them if this functionality is of interest to you. The verbosity of enumerating all of the combinations of these methods would be of low value. You will get far more value out of using them and discovering for yourself.

As we delve deeper into the depths of what the Rx libraries provide us, we can see more practical usages for it. Composing sequences with Rx allows us to easily make sense of the multiple data sources a problem domain is exposed to. We can concatenate values or sequences together sequentially with StartWith, Concat and Repeat. We can process multiple sequences concurrently with Merge, or process a single sequence at a time with Amb and Switch. Pairing values with CombineLatest, Zip and the And/Then/When operators can simplify otherwise fiddly operations like our drag-and-drop examples and monitoring system status.

stackover flow 上面的例子

https://stackoverflow.com/questions/38595386/rxjs-and-thendo-when-example

var selector = function (x, y) { return x + ", " + y; };

var source = Rx.Observable.when(
    Rx.Observable.interval(250).and(Rx.Observable.of("A", "B", "C")).thenDo(selector),
    Rx.Observable.interval(300).and(Rx.Observable.of("a", "b")).thenDo(selector)
);

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

// => Next: 0, A 
// => Next: 0, a
// => Next: 1, B
// => Next: 1, b
// => Next: 2, C
// => Completed

看上面的这段代码,就能知道And/Then(ThenDo)/When是什么意思! Rx.Observable.interval(250)这段代码的意思就是隔开指定的时间就开始向外面发射整数数据,所以会发射出:0,1,2........但是因为后面需要合并的Observable中只是有三个数据,所以只会取出Rx.Observable.interval(250)中的三个数据,而不会取出后面的数据。

2017-08-28_114418

Christian-health commented 6 years ago

any / Contains / findIndex / indexOf / isEmpty

determine whether an Observable emits a particular item or not 确定Observable是否发出特定的项目

image

Pass the Contains operator a particular item, and the Observable it returns will emit true if that item is emitted by the source Observable, or false if the source Observable terminates without emitting that item. 意思就是这个Contains操作符号,它接受一个Observable作为源,然后它的输出也是一个Observable, 如果输入的Observable中发射出了指定的值,那么输出的Observable中就是true,否则就是false。

A related operator, IsEmpty returns an Observable that emits true if and only if the source Observable completes without emitting any items. It emits false if the source Observable emits an item. 相关的运算符IsEmpty返回一个Observable,当且仅当源Observable完成而不发出任何项时才会发送true。 如果源Observable发出一个项目,它会发出false。

image

The contains operator in RxJS takes an optional second parameter: a zero-based index into the source Observable’s sequence at which to start searching for the item.

RxJS中的contains运算符采用可选的第二个参数:从源Observable的序列开始搜索该项目的基于零的索引。(意思就是说Contains操作符,还可以有第二个参数,这个参数可以指定Observable从第几个值开始进行操作,默认是从index=0的位置开始,但是我们也可以指定一个值,这样就可以从index=n的位置开始)

/* Without an index */
var source = Rx.Observable.of(42)
  .contains(42);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
Next: true
Completed
/* With an index */
var source = Rx.Observable.of(1,2,3)
  .contains(2, 1);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
Next: true
Completed

indexOf

image

The indexOf operator in RxJS is similar to contains but rather than returning an Observable that emits true or false it returns an Observable that emits the index of the item in the source Observable sequence, or −1 if no such item was emitted. RxJS中的indexOf运算符类似于包含但不是返回一个发出true或false的Observable,而是返回一个Observable,该Observable会在源Observable序列中发出该项的索引,如果没有发出这样的项,则返回-1。

The indexOf operator takes an optional second parameter: a zero-based index into the source Observable’s sequence at which to start searching for the item. The index value that the resulting Observable emits will be relative to this start point, not to the beginning of the sequence. indexOf运算符接受可选的第二个参数:基于零的索引到源Observable的序列中开始搜索该项目。 所得到的Observable发出的索引值将相对于该起始点,而不是序列的开头。

/* Without an index */
var source = Rx.Observable.of(42)
  .indexOf(42);

var subscription = source.subscribe(
  function (x) { console.log('Next: %s', x); },
  function (err) { console.log('Error: %s', err); },
  function () { console.log('Completed'); });
Next: 0 
Completed
/* With an index */
var source = Rx.Observable.of(1,2,3)
  .indexOf(2, 1); //从下标为1的元素开始查找值为2并且输出一个包含这个位置值的Observable 

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

findIndex

image

The findIndex operator in RxJS takes as its parameter a predicate function. It returns an Observable that emits either a single number — the zero-based index of the first item in the source Observable sequence that matches the predicate — or −1 if no such item matches.

RxJS中的findIndex运算符作为其参数的谓词函数。 它返回一个Observable,它发出单个数字 - 源Observable序列中与谓词匹配的第一个项目的从零开始的索引 - 如果没有这样的项目匹配,则返回-1。

The predicate function takes three parameters: 谓词函数有三个参数:

You can also pass an object to findIndex as an optional second parameter, and that object will be available to the predicate function as “this”.

/* Found an element */
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 1;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: 0
Completed
/* Not found */
var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 5;
    });

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

看下面这个图,可以看到谓词函数的三个参数。其中的第三个参数,就是一个Observable,也就是源Observable 1

isEmpty

image

RxJS also implements the isEmpty operator. The Observable returned from isEmpty will return false if the source Observable emits an item, and true if it completes without emitting an item. RxJS还实现了isEmpty运算符。 如果源Observable发出一个项目,则isEmpty返回的Observable将返回false,如果没有发出项目,则返回true。

/* Not empty */
var source = Rx.Observable.range(0, 5)
    .isEmpty()

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: false
Completed
/* Empty */
var source = Rx.Observable.empty()
    .isEmpty()

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: true
Completed
Christian-health commented 6 years ago

apply (Create)

generate

generateWithRelativeTime

generateWithAbsoluteTime

Create 操作符

create an Observable from scratch by means of a function. 通过一个函数从头创建一个Observable。

create

You can create an Observable from scratch by using the Create operator. You pass this operator a function that accepts the observer as its parameter. Write this function so that it behaves as an Observable — by calling the observer’s onNext, onError, and onCompleted methods appropriately.

您可以使用Create操作符从头创建一个Observable。 您通过此操作符接受观察者作为其参数的函数。 编写这个函数,使其表现为一个Observable - 通过适当地调用观察者的onNext,onError和onCompleted方法。 (也就是说这个create函数的参数应该像一个observer,这个observer里面应该有onNext,onError和onCompleted方法)

A well-formed finite Observable must attempt to call either the observer’s onCompleted method exactly once or its onError method exactly once, and must not thereafter attempt to call any of the observer’s other methods. 一个格式良好的Observable必须尝试一次调用观察者的onCompleted方法或者其onError方法一次,而且此后不能尝试调用任何观察者的其他方法。

/* Using a function  使用一个函数*/
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
    //请注意,这是可选的,如果不需要清理,则不需要返回
    return function () { console.log('disposed'); };
});

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

运行结果

Next: 42
Completed
/* Using a disposable 使用一次性 */
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
   //请注意,这是可选的,如果不需要清理,则不需要返回
    return Rx.Disposable.create(function () {
        console.log('disposed');
    });
});

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

Next: 42
Completed

Rx.Observable.create

var observable = Rx.Observable
    .create(function(observer) {
        observer.next('Semlinker'); // RxJS 4.x 以前的版本用 onNext
        observer.next('Lolo');
    });

// 订阅这个 Observable    
observable.subscribe(function(value) {
    console.log(value);
});

以上代码运行后,控制台会依次输出 'Semlinker' 和 'Lolo' 两个字符串。

需要注意的是,很多人认为 RxJS 中的所有操作都是异步的,但其实这个观念是错的。RxJS 的核心特性是它的异步处理能力,但它也是可以用来处理同步的行为。具体示例如下:

var observable = Rx.Observable
    .create(function(observer) {
        observer.next('Semlinker'); // RxJS 4.x 以前的版本用 onNext
        observer.next('Lolo');
    });

console.log('start');
observable.subscribe(function(value) {
    console.log(value);
});
console.log('end');

以上代码运行后,控制台的输出结果://ExJs用来处理同步行为

start
Semlinker
Lolo
end

当然我们也可以用它处理异步行为:

var observable = Rx.Observable
    .create(function(observer) {
        observer.next('Semlinker'); // RxJS 4.x 以前的版本用 onNext
        observer.next('Lolo');

        setTimeout(() => {
            observer.next('RxJS Observable');
        }, 300);
    })

console.log('start');
observable.subscribe(function(value) {
    console.log(value);
});
console.log('end');

以上代码运行后,控制台的输出结果://RxJs用来处理异步行为

start
Semlinker
Lolo
end
RxJS Observable

从以上例子中,我们可以得出一个结论 - Observable 可以应用于同步和异步的场合。

generate

image

You can use the generate operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of generate takes four parameters: 您可以使用generate运算符创建简单的可观测值,可以生成其下一个排放,并可以根据先前排放的值确定何时终止。 生成的基本形式有四个参数:

You can also pass in as an optional fifth parameter a Scheduler that generate will use to create and emit its sequence (it uses currentThread by default). 您还可以作为可选的第五个参数传入生成将用于创建和发布其序列的调度程序(默认情况下使用currentThread)。

var source = Rx.Observable.generate(
    0,// 将要发射的第一个item
    function (x) { return x < 3; }, //  一个函数用来测试一个item然后去决定是否发射它,或者终结这个Observable
    function (x) { return x + 1; },//   一个函数用来产生下一个用来测试的item,并且根据前一个item来决定是否发射它。
    function (x) { return x; }//  一个函数用来在发射之前对item进行转换
);

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

generateWithRelativeTime

image You can use the generateWithRelativeTime operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of generateWithRelativeTime takes five parameters: 您可以使用generateWithRelativeTime运算符创建简单的可观测值,可以生成其下一个排放,并可根据先前排放的值确定何时终止。 generateWithRelativeTime的基本形式有五个参数:

var subscription = source.subscribe( function (x) { console.log('Next: ' + x); }, function (err) { console.log('Error: ' + err); }, function () { console.log('Completed'); }); Next: {value: 1, interval: 100} //Observable开始之后100毫秒发出value 1 Next: {value: 2, interval: 200} //value 1发出200毫秒之后发出value 2 Next: {value: 3, interval: 300} // value 2发出300毫秒之后发出value 3 Completed

# generateWithAbsoluteTime
![image](https://user-images.githubusercontent.com/29979200/29761947-7fa48a50-8b91-11e7-91b0-97452ae70a7c.png)

You can use the generateWithAbsoluteTime operator to create simple Observables that can generate their next emissions, and can determine when to terminate, based on the value of the previous emission. The basic form of generateWithAbsoluteTime takes five parameters:
您可以使用generateWithAbsoluteTime运算符创建简单的可观测值,可以生成其下一个排放,并可以根据先前排放的值确定何时终止。 generateWithAbsoluteTime的基本形式有五个参数:

- the first item to emit
  将要发射的第一个item
- a function to test an item to determine whether to emit it (true) or terminate the Observable (false)
   一个函数用来测试一个item然后去决定是否发射它,或者终结这个Observable
- a function to generate the next item to test and emit based on the value of the previous item
   一个函数用来产生下一个用来测试的item,并且根据前一个item来决定是否发射它。
- a function to transform items before emitting them
  一个函数用来在发射之前对item进行转换
- a function to indicate at what time (expressed as a Date) the generator should emit the the new item
   指示在什么时间(表示为Date)的函数,发生器应该发出新的项目
You can also pass in as an optional sixth parameter a Scheduler that generate will use to create and emit its sequence (it uses currentThread by default).
您还可以作为可选的第五个参数传入生成将用于创建和发布其序列的调度程序(默认情况下使用currentThread)

var source = Rx.Observable.generate( 1, function (x) { return x < 4; }, function (x) { return x + 1; }, function (x) { return x; }, function (x) { return Date.now() + (100 * x); } ).timeInterval();

var subscription = source.subscribe( function (x) { console.log('Next: ' + x); }, function (err) { console.log('Error: ' + err); }, function () { console.log('Completed'); }); Next: {value: 1, interval: 100} Next: {value: 2, interval: 200} Next: {value: 3, interval: 300} Completed

Christian-health commented 6 years ago

as_blocking (To)

toArray

toMap

toSet

convert an Observable into another object or data structure 将Observable转换为另一个对象或数据结构

image

The various language-specific implementations of ReactiveX have a variety of operators that you can use to convert an Observable, or a sequence of items emitted by an Observable, into another variety of object or data structure. Some of these block until the Observable terminates and then produce an equivalent object or data structure; others return an Observable that emits such an object or data structure.

ReactiveX的各种语言特定的实现具有多种运算符,您可以使用它们将Observable或Observable发出的一系列项目转换为另一种对象或数据结构。 其中一些阻塞直到Observable终止,然后产生等效的对象或数据结构; 其他人返回一个发出这样一个对象或数据结构的Observable。

In some implementations of ReactiveX, there is also an operator that converts an Observable into a “Blocking” Observable. A Blocking Observable extends the ordinary Observable by providing a set of methods, operating on the items emitted by the Observable, that block. Some of the To operators are in this Blocking Obsevable set of extended operations. 在ReactiveX的一些实现中,还有一个将Observable转换为“Blocking”Observable的操作符。 Blocking Observable通过提供一组方法来扩展普通Observable,该方法对Observable发出的项目进行操作。 一些To操作符在这个Blocking Obsevable集合的扩展操作中。

image Normally, an Observable that emits multiple items will do so by invoking its observer’s onNext method for each such item. You can change this behavior, instructing the Observable to compose an array of these multiple items and then to invoke the observer’s onNext method only once, passing it the entire array, by applying the toArray operator to the Observable. 通常,发出多个项目的Observable将通过为每个这样的项目调用其观察者的onNext方法来实现。 您可以更改此行为,指示Observable组合这些多个项目的数组,然后仅将观察者的onNext方法调用一次,传递整个数组,方法是将toArray运算符应用于Observable。 (这段话的意思就是,原来的时候一个Observable,一个一个的发出数据,然后我们可以使用take(5)这样的运算符号,取出其中的若干个,然后通过toArray运算符这样的符号把发出的这若干个item数据整合成为一个数组,然后把这个数组整体作为一个item发射出去)

var source = Rx.Observable.timer(0, 1000)
    .take(5)
    .toArray();

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

toMap

image The toMap operator collects the items emitted by the source Observable into a Map and then emits that map. You supply a function that generates the key for each emitted item. You may also optionally supply a function that converts an emitted item into the value to be stored in the map (by default, the item itself is this value).

var source = Rx.Observable.timer(0, 1000)
    .take(5)
    .toMap(
                          function (x) { 
                          // 第一个函数是key
                          return x * 2; 
                         }, 
                         function (x) { 
                         // 第二个函数是value
                         return x * 4; 
                         }
);

var subscription = source.subscribe(
    function (x) {
        var arr = [];
        x.forEach(function (value, key) { arr.push(value, key); })
        console.log('Next: ' + arr);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: [0,0,2,4,4,8,6,12,8,16]
Completed

image

Normally, an Observable that emits multiple items will do so by invoking its observer’s onNext method for each such item. You can change this behavior, instructing the Observable to compose a Set of these multiple items and then to invoke the observer’s onNext method only once, passing it the entire Set, by applying the toSet operator to the Observable.

Note that this only works in an ES6 environment or polyfilled.

var source = Rx.Observable.timer(0, 1000) //从0时间开始,每隔1S发出一个整数
    .take(5)
    .toSet();

var subscription = source.subscribe(
    function (x) {
        var arr = [];
        x.forEach(function (i) { arr.push(i); })
        console.log('Next: ' + arr);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: [0,1,2,3,4]
Completed
Christian-health commented 6 years ago

asObservable

From 操作符

convert various other objects and data types into Observables 将各种其他对象和数据类型转换为Observables

When you work with [Observables], it can be more convenient if all of the data you mean to work with can be represented as [Observables], rather than as a mixture of [Observables] and other types. This allows you to use a single set of operators to govern the entire lifespan of the data stream. 当您使用[Observables]时,如果您要使用的所有数据都可以表示为[Observables],而不是[Observables]和其他类型的混合,则可以更方便。 这允许您使用一组运算符来管理数据流的整个生命周期。

Iterables, for example, can be thought of as a sort of synchronous Observable; Futures, as a sort of Observable that always emits only a single item. By explicitly converting such objects to Observables, you allow them to interact as peers with other Observables. 例如,Iterables可以被认为是一种同步的Observable; Futures,作为一种可观察,总是只发出一个项目。 通过明确地将这些对象转换为Observables,您可以让它们与其他Observables进行交互。

For this reason, most ReactiveX implementations have methods that allow you to convert certain language-specific objects and data structures into Observables. 因此,大多数ReactiveX实现具有允许您将某些特定语言的对象和数据结构转换为Observables的方法。 from In RxJS, the from operator converts an array-like or iterable object into an Observable that emits the items in that array or iterable. A String, in this context, is treated as an array of characters.

在RxJS中,from操作符将数组或可迭代对象转换为Observable,该对象可发出该数组中的项或iterable(迭代器)。 在此上下文中,String被视为字符数组。

This operator also takes three additional, optional parameters: 该操作符还需要三个可选参数: 2:a transforming function that takes an item from the array or iterable as input and produces an item to be emitted by the resulting Observable as output 一个转换函数,它从数组中获取一个项,或者一个迭代器作为输入,并产生由Observable作为输出发出的项目 3:a second argument to pass into the transforming function as additional context information 第二个参数作为附加上下文信息传递给转换函数 4:a Scheduler on which this operator should operate 这个操作符应该操作的一个计划程序(Scheduler)

from(参数1,参数2,参数3,参数4)
            ||
            ||
            \/
from(参数1,转换函数,转换函数的另外一个参数,Scheduler)

代码举例:

这里的arguments是JavaScript arguments对象,可以看这里进行了解:http://www.cnblogs.com/lwbqqyumidi/archive/2012/12/03/2799833.html

 Array-like object (arguments) to Observable
类似Array的对象(arguments)到Observable
function f() {
// 这里的arguments是JavaScript arguments对象,可以看这里进行了解:

http://www.cnblogs.com/lwbqqyumidi/archive/2012/12/03/2799833.html

  return Rx.Observable.from(arguments);
}
f(1, 2, 3).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
// Any iterable object...
// Set
var s = new Set(['foo', window]);
Rx.Observable.from(s).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
Next: foo
Next: window
Completed
// Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Rx.Observable.from(m).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
Next: [1, 2]
Next: [2, 4]
Next: [4, 8]
Completed
// String
Rx.Observable.from("foo").subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
Next: f
Next: o
Next: o
Completed

使用from函数第二个参数的例子:from([1, 2, 3], function (x) { return x + x; })

// Using an arrow function as the map function to manipulate the elements
Rx.Observable.from([1, 2, 3], function (x) { return x + x; }).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
Next: 2
Next: 4
Next: 6
Completed

Rx.Observable.from({length: 5}, function(v, k) { return k; })的工作原理:

array 原理就是,javascript使用鸭子类型,当你想调用一个Object中的foo方法的时候,如果这个Object是bar类型。也就是说typeof Object = bar 。它并不检查这个Object到底是否真是一个bar类型,javascript只检测这个Object中是否有这个foo方法。

To sum up: 总结一下:

let fakeArray = {length:5};
fakeArray.length //5
let realArray = [1,2,3,4,5];
realArray.length //5

第一个就像“假的”JavaScript数组(具有属性长度)。 当Array.from检查属性长度时,它返回5,因此它创建具有长度为5的真实数组。您可以想数组一样的调用它,并认为它是一个数组。然后会自动的使用Array.from()函数创建一个数组,Array.from()函数的信息: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from 第二部分只是lamba,它使用索引值(第二个参数)填充数组。也就是调用Array.from这个函数来填充数组。 这种技术对于mock某些对象(仿真某些对象,假对象)进行测试非常有用。 例如:

let ourFileReader = {}
ourFileReader.result = "someResult"
//ourFileReader will mock real FileReader
我们的FileReader会模拟真正的FileReader

var arr1 = Array.from({ length: 5 // Create 5 indexes with undefined values }, function(v, k) { // Run a map function on said indexes using v(alue)[undefined] and k(ey)[0 to 4] return k; // Return k(ey) as value for this index } ); console.log(arr1);

https://stackoverflow.com/questions/40528557/how-does-array-fromlength-5-v-k-k-work

// Generate a sequence of numbers
Rx.Observable.from({length: 5}, function(v, k) { return k; }).subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); });
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed

fromCallback

image

The fromCallback operator takes a function as a parameter, calls this function, and emits the value returned from it as its single emission. fromCallback运算符将一个函数作为参数,调用此函数,并将其返回的值作为单个发射发出。

This operator also takes two additional, optional parameters: 此运算符还需要两个额外的可选参数:

var fs = require('fs'),//node Js中的文件操作
    Rx = require('rx');

// Wrap fs.exists
var exists = Rx.Observable.fromCallback(fs.exists);//将fx.exists函数作为回调函数。

// Check if file.txt exists
var source = exists('file.txt');  //如果这个文件存在那么就返回true,如果这个函数不存在那么就返回fasle

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

fromNodeCallback

There is also a fromNodeCallback operator, which is specialized for the types of callback functions found in Node.js. 还有一个fromNodeCallback运算符,这个操作符专门用于指定在nodeJS中找到的回调函数的类型。

This operator takes three additional, optional parameters: 还有三个额外的可选的操作符: 2、a Scheduler on which you want to run the Node.js callback 您要在其上运行Node.js回调的Scheduler计划程序 3、a parameter to give to the callback function 一个给予回调函数的参数 4、a tranforming function that takes the return value of the callback function as input and returns an item to be emitted by the resulting Observable 一个转换函数,它将回调函数的返回值作为输入返回一个待生成的Observable发出的项 (就是说可以对回调函数的值进行操作,然后再将这个操作之后的值返回出来)

var fs = require('fs'),
    Rx = require('rx');

// fs.rename和fs.exists两个函数是nodeJS的专有函数
// Wrap fs.exists
var rename = Rx.Observable.fromNodeCallback(fs.rename);

// Rename file which returns no parameters except an error
var source = rename('file1.txt', 'file2.txt');

var subscription = source.subscribe(
    function () { console.log('Next: success!'); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: success!
Completed

fromEvent

image

The fromEvent operator takes an “element” and an event name as parameters, and it then listens for events of that name taking place on that element. It returns an Observable that emits those events. An “element” may be a simple DOM element, or a NodeList, jQuery element, Zepto Element, Angular element, Ember.js element, or EventEmitter. fromEvent操作符将“元素”和"事件名称"作为参数,然后监听该元素上发生的该名称的事件。 它返回一个发出这些事件的Observable。 “元素”可以是简单的DOM元素,或者NodeList,jQuery元素,Zepto元素,angular元素,Ember.js元素或EventEmitter。

This operator also takes an optional third parameter: a function that accepts the arguments from the event handler as parameters and returns an item to be emitted by the resulting Observable in place of the event. 此运算符还使用可选的第三个参数:

// using a jQuery element
var input = $('#input');

var source = Rx.Observable.fromEvent(input, 'click');

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

input.trigger('click');
Next: Clicked!
// using a Node.js EventEmitter and the optional third parameter
var EventEmitter = require('events').EventEmitter,
    Rx = require('rx');

var eventEmitter = new EventEmitter();
//这段代码的意思是,监听事件发射,也就是eventEmitter,相当与上面的那个程序中的Dom元素。
也就是事件的来源。第二个参数是表示什么事件,如果是名字叫做data的事件发生了,那么就运行
fromEvent()。这个fromEvent()函数头两个参数,肯定一个是事件源,另外一个是事件的名字。
var source = Rx.Observable.fromEvent(
    eventEmitter,
    'data',
    function (first, second) {
        return { foo: first, bar: second };
    });

var subscription = source.subscribe(
    function (x) {
        console.log('Next: foo -' + x.foo + ', bar -' + x.bar);
    },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

eventEmitter.emit('data', 'baz', 'quux');
程序结果:
Next: foo - baz, bar - quux

fromEventPattern

The fromEventPattern operator is similar, except that instead of taking an element and an event name as parameters, it takes two functions as parameters. The first function attaches an event listener to a variety of events on a variety of elements; the second function removes this set of listeners. In this way you can establish a single Observable that emits items representing a variety of events and a variety of target elements. fromEventPattern操作符是类似的,除了将元素和事件名称作为参数,它以两个函数为参数 (就是说这个函数和fromEvent函数功能类似,但是不同的地方是这个函数使用两个函数作为参数)。 第一个函数将事件监听器附加到各种元素上的各种事件; 第二个函数删除这组监听器。 以这种方式,您可以建立一个可观察到的,发出表示各种事件和各种目标元素的项目。

注意下面这段代码,如果想要在html中运行,那么需要在html中创建一个

var input = $('#input');

var source = Rx.Observable.fromEventPattern(
    function add (h) {
        input.bind('click', h);
    },
    function remove (h) {
        input.unbind('click', h);
    }
);

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

input.trigger('click');
Next: Clicked!

of

image The of operator accepts a number of items as parameters, and returns an Observable that emits each of these parameters, in order, as its emitted sequence. 运算符接受多个项目作为参数,并返回一个Observable,按照排列顺序发射这些东西。

var source = Rx.Observable.of(1,2,3);

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

ofWithScheduler

A variant of this operator, called ofWithScheduler takes a Scheduler as its first parameter, and operates the resulting Observable on this Scheduler.

fromPromise

There is also a fromPromise operator that converts a Promise into an Observable, converting its resolve calls into onNext notifications, and its reject calls into onError notifications.

var promise = new RSVP.Promise(function (resolve, reject) {
   resolve(42);
});

var source = Rx.Observable.fromPromise(promise);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
Next: 42:
Completed
var promise = new RSVP.Promise(function (resolve, reject) {
   reject(new Error('reason'));
});

var source = Rx.Observable.fromPromise(promise);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
Error: Error: reject

ofArrayChanges

There is also an ofArrayChanges operator that monitors an Array with the Array.observe method, and returns an Observable that emits any changes that take place in the array. This operator is found only in the rx.all.js distribution.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <script type="text/javascript" src="./RxJS-master/dist/rx.all.js"></script>
    <!-- <script type="text/javascript" src="./yang.js"></script> -->
</head>
<body>
<script>
var arr = [1,2,3];
var source = Rx.Observable.ofArrayChanges(arr);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + JSON.stringify(x)); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });

arr.push(4)
</script>
</body>
</html>

程序运行结果(自己在浏览器上运行的结果):
Next: {"type":"splice","object":[1,2,3,4],"index":3,"removed":[],"addedCount":1}

Next: {type: "splice", object: Array[4], index: 3, removed: Array[0], addedCount: 1}

ofObjectChanges

A similar operator is ofObjectChanges. It returns an Observable that emits any changes made to a particular object, as reported by its Object.observe method. It is also found only in the rx.all.js distribution.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <script type="text/javascript" src="./RxJS-master/dist/rx.all.js"></script>
    <!-- <script type="text/javascript" src="./yang.js"></script> -->
</head>
<body>
<script>
var obj = {x: 1};
var source = Rx.Observable.ofObjectChanges(obj);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + JSON.stringify(x)); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });

obj.x = 42;
</script>
</body>
</html>
程序运行结果(自己在浏览器上运行的):
Next: {"type":"update","object":{"x":42},"name":"x","oldValue":1}
官方给出的运行结果:
Next: {type: "update", object: Object, name: "x", oldValue: 1}

pairs

There is also a pairs operator. This operator accepts an Object, and returns an Observable that emits, as key/value pairs, the attributes of that object.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <script type="text/javascript" src="./RxJS-master/dist/rx.all.js"></script>
    <!-- <script type="text/javascript" src="./yang.js"></script> -->
</head>
<body>
<script type="text/javascript">
var obj = {
  foo: 42,
  bar: 56,
  baz: 78
};

var source = Rx.Observable.pairs(obj);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x,'typeof x:',typeof x); },
  // function (x) { console.log('Next: ' + x); },
    function (e) { console.log('Error: ' + e); },
    function ( ) { console.log('Completed'); });
</script>
</body>
</html>

Next: foo,42 typeof x: object
Next: bar,56 typeof x: object
Next: baz,78 typeof x: object
Completed
Christian-health commented 6 years ago

AssertEqual (SequenceEqual)

determine whether two Observables emit the same sequence of items 确定两个Observables是否发出相同的项目序列 image Pass SequenceEqual two Observables, and it will compare the items emitted by each Observable, and the Observable it returns will emit true only if both sequences are the same (the same items, in the same order, with the same termination state). 传递给 SequenceEqual操作符两个Observables,它将比较每个Observable发出的项目,只有两个序列相同(相同的项目,相同的顺序,具有相同的终止状态),它才返回的Observable将发送true。

image

In RxJS, sequenceEqual is a method of a particular Observable instance, so you pass it exactly one other Observable to compare the instance to. You can optionally pass a second parameter: a function that accepts two items and returns true if they are equal according to a standard of your choosing. sequenceEqual returns an Observable that will emit a true if the two Observables emit the same set of items in the same order before completing, or a false otherwise.

在RxJS中,sequenceEqual是特定Observable实例的一种方法,因此您可以将其与另一个Observable进行比较,以将该实例进行比较。 您可以选择传递第二个参数:一个接受两个项目的函数,如果根据您选择的标准相等则返回true。 sequenceEqual返回一个Observable,如果两个Observables在完成之前以相同的顺序排列相同的一组项,则返回true,否则返回false。

var source1 = Rx.Observable.return(42);
var source2 = Rx.Observable.return(42);

var source = source1.sequenceEqual(source2);//sequenceEqual操作符返回一个Observable

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: true
Completed
Christian-health commented 6 years ago

asyncAction (Start)

startAsync

start用来处理同步函数

create an Observable that emits the return value of a function-like directive 创建一个Observable,这个Observable发射指令的返回值,这个指令像一个函数一样会有返回值。 image

There are a number of ways that programming languages have for obtaining values as the result of calculations, with names like functions, futures, actions, callables, runnables, and so forth. The operators grouped here under the Start operator category make these things behave like Observables so that they can be chained with other Observables in an Observable cascade 编程语言有许多方法用于获得作为计算结果的值,其名称类似于函数,特性,动作,可调用性,可运行性等。 在[Start]运算符类别下分组的运算符使得这些操作类似于Observables,以便它们可以与可观察级联中的其他Observables链接 image

RxJS implements the start operator. It takes as its parameters a function whose return value will be the emission from the resulting Observable, and, optionally, any additional parameter to that function and a Scheduler on which to run the function. RxJS实现[start]运算符。 它的参数是一个函数,这个函数的返回值将会是start运算符形成的Observable中发射出去的值。并且,可选的,任意的附加的参数给这个函数参数。最后是一个这个函数调度时候的Scheduler

解释:start这个运算符有三个参数: (1)一个函数,这个函数会返回一个值 (2)第一个参数,也就是那个函数的可选参数,(也就是说第二个参数,完全是为了给第一个参数服务的) (3)一个调度器

var context = { value: 42 };

var source = Rx.Observable.start(
    function () {     //参数1
        return this.value;
    },
    context, //参数2
    Rx.Scheduler.timeout //参数3
);

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

startAsync用来处理异步函数

image

RxJS also implements the startAsync operator. It takes as its parameters an asynchronous function whose return value will be the emission from the resulting Observable. RxJS还实现了startAsync运算符。 它将其作为参数作为异步函数,其返回值将来自所得到的Observable的发射。 You can convert a function into an asynchronous function with the toAsync method. It takes a function, function parameter, and Scheduler as parameters, and returns an asynchronous function that will be invoked on the specified Scheduler. The last two parameters are optional; if you do not specify a Scheduler, the timeout Scheduler will be used by default. 您可以使用toAsync方法将函数转换为异步函数。 它将一个函数,函数参数和Scheduler作为参数,并返回将在指定的Scheduler上调用的异步函数。 最后两个参数是可选的; 如果不指定调度程序,默认情况下将使用超时计划程序。

解释:startAsync这个运算符有三个参数: (1)一个函数,这个函数会返回一个值,这个值不是一个同步的值,而是一个异步的值 (2)第一个参数,也就是那个函数的可选参数,(也就是说第二个参数,完全是为了给第一个参数服务的) (3)一个调度器,默认情况下是timeout Scheduler超时调度器

var source = Rx.Observable.startAsync(function () {
    return RSVP.Promise.resolve(42);
});

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });
Next: 42
Completed
Christian-health commented 6 years ago

Average

averageDouble

averageFloat

averageInteger

averageLong

calculates the average of numbers emitted by an Observable and emits this average 12225 计算Observable发射的数字的平均值,并发射该平均值

image

The Average operator operates on an Observable that emits numbers (or items that can be evaluated as numbers), and emits a single value: the average of all of the numbers emitted by the source Observable.

平均值运算符对可发出数字(或可被评估为数字的项目)的Observable进行操作,并发出单个值:源Observable发出的所有数字的平均值。

image

var source = Rx.Observable.range(0, 9).average();

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

image

You can also average not the items themselves but the results of a function applied to each item, as in the illustration above, which emits the average number of sides on the figures emitted by the source Observable. 您也可以平均不是项目本身,而是作用于项目本身的函数的结果,如上图所示,它发出源Observable发出的数字的平均数。

var arr = [
    { value: 1 },
    { value: 2 },
    { value: 3 }
];

var source = Rx.Observable.fromArray(arr).average(function (x) {
    return x.value;
});

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