create

函数签名: create(subscribe: function)

使用给定的订阅函数来创建 observable 。

示例

示例 1: 发出多个值的 observable

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { Observable } from 'rxjs';
/*
  创建在订阅函数中发出 'Hello' 和 'World' 的 observable 。
*/
const hello = Observable.create(function(observer) {
  observer.next('Hello');
  observer.next('World');
});

// 输出: 'Hello'...'World'
const subscribe = hello.subscribe(val => console.log(val));
示例 2: 基于定时器发出偶数的 observable

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { Observable } from 'rxjs';

/*
  每秒自增值并且只发出偶数
*/
const evenNumbers = Observable.create(function(observer) {
  let value = 0;
  const interval = setInterval(() => {
    if (value % 2 === 0) {
      observer.next(value);
    }
    value++;
  }, 1000);

  return () => clearInterval(interval);
});
// 输出: 0...2...4...6...8
const subscribe = evenNumbers.subscribe(val => console.log(val));
// 10秒后取消订阅
setTimeout(() => {
  subscribe.unsubscribe();
}, 10000);

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/GenerateObservable.ts

results matching ""

    No results matching ""