[关闭]
@duanyubin 2017-04-10T13:22:09.000000Z 字数 2286 阅读 322

Rx: 更好的异步流程控制

javascript


https://www.youtube.com/watch?v=3LKMwkuK0ZE
https://www.youtube.com/watch?v=ei7FsoXKPl0

What is RxJS

RxJS is a library for composing asynchronous and event-based programs
Think of RxJS as Lodash for events.

Here should be some examples

  1. const btn1$ = Observable.fromEvent($('.btn1'), 'click')
  2. btn1$
  3. .scan(count => count + 1, 0)
  4. .subscribe((val) => {
  5. $('.text').text(`You have survived The Older for ${val} Seconds`)
  6. })
  7. -------c-------c-----c-----|--->

Concept

Observable

Think of it as Asynchronous ArrayPromiseFunction

value + timeline = Observable

Create an Observable

  1. const observable = Rx.Observable.create(function (observer) {
  2. observer.next(1);
  3. observer.next(2);
  4. observer.next(3);
  5. setTimeout(() => {
  6. observer.next(4);
  7. observer.complete();
  8. }, 1000);
  9. });
  10. console.log('just before subscribe');
  11. observable.subscribe({
  12. next: x => console.log(x),
  13. error: err => console.error('something wrong occurred: ' + err),
  14. complete: () => console.log('done'),
  15. });
  16. console.log('just after subscribe');
  17. // logs
  18. // just before subscribe
  19. // 1..2..3
  20. // just After subscribe
  21. // 4
  22. // done

Think as Promise

  1. promise.then(
  2. successFn,
  3. errorFn
  4. )
  5. observable.subscribe(
  6. successFn,
  7. errorFn,
  8. completeFn
  9. )

Without Operators, Observable are no scarier than Promise

Difference from Promise

Promise Observable
Value amount Single Mutilple
Evaluate Immediate Lazy
Cancelable No Yes
Retry No Yes

Think as Function

  1. function foo () {}
  2. foo.call()
  3. observable.susbscribe()

Functions dont do any thing until they are called
Observables dont do any thing utils they are subscribed

Observer

Observers are just objects with three callbacks, one for each type of notification that an Observable may deliver.

  1. var observer = {
  2. next: x => console.log('Observer got a next value: ' + x),
  3. error: err => console.error('Observer got an error: ' + err),
  4. complete: () => console.log('Observer got a complete notification'),
  5. }

Operator

What Operator do i use ?

Examples

Use RxJS where its best suited

Do NOT use Rx when its not needed

Thinking Reactively

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注