RxJS源码解读之生成observable的函数

生成observable的函数

Rxjs中大概提供了32个函数,这些函数执行都返回Observable实例。

RxJS源码解读之生成observable的函数_第1张图片
avatar

用法示例

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

// 将数组作为值的序列发出
const arraySource = from([1, 2, 3, 4, 5]);
// 输出: 1,2,3,4,5
const subscribe = arraySource.subscribe(val => console.log(val));

源码

以fromArray为例

/**
 * Subscribes to an ArrayLike with a subscriber
 * @param array The array or array-like to subscribe to
 */
export const subscribeToArray = (array: ArrayLike) => (subscriber: Subscriber) => {
  for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {
    subscriber.next(array[i]);
  }
  if (!subscriber.closed) {
    subscriber.complete();
  }
};

export function fromArray(input: ArrayLike, scheduler?: SchedulerLike) {
  if (!scheduler) {
    return new Observable(subscribeToArray(input));
  } else {
    return new Observable(subscriber => {
      const sub = new Subscription();
      let i = 0;
      sub.add(scheduler.schedule(function () {
        if (i === input.length) {
          subscriber.complete();
          return;
        }
        subscriber.next(input[i++]);
        if (!subscriber.closed) {
          sub.add(this.schedule());
        }
      }));
      return sub;
    });
  }
}

你可能感兴趣的:(RxJS源码解读之生成observable的函数)