startWith

函数签名: startWith(an: Values): Observable

发出给定的第一个值


:bulb: BehaviorSubject 也可以从初始值开始!


示例

( 示例测试 )

示例 1: 对数字序列使用 startWith

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { startWith } from 'rxjs/operators';
import { of } from 'rxjs';

// 发出 (1,2,3)
const source = of(1, 2, 3);
// 从0开始
const example = source.pipe(startWith(0));
// 输出: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));
示例 2: startWith 用作 scan 的初始值

( StackBlitz | | jsBin | jsFiddle )

// RxJS v6+
import { startWith, scan } from 'rxjs/operators';
import { of } from 'rxjs';

// 发出 ('World!', 'Goodbye', 'World!')
const source = of('World!', 'Goodbye', 'World!');
// 以 'Hello' 开头,后面接当前字符串
const example = source.pipe(
  startWith('Hello'),
  scan((acc, curr) => `${acc} ${curr}`)
);
/*
  输出:
  "Hello"
  "Hello World!"
  "Hello World! Goodbye"
  "Hello World! Goodbye World!"
*/
const subscribe = example.subscribe(val => console.log(val));
示例 3: 使用多个值进行 startWith

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { startWith } from 'rxjs/operators';
import { interval } from 'rxjs';

// 每1秒发出值
const source = interval(1000);
// 以 -3, -2, -1 开始
const example = source.pipe(startWith(-3, -2, -1));
// 输出: -3, -2, -1, 0, 1, 2....
const subscribe = example.subscribe(val => console.log(val));

相关食谱

其他资源


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

results matching ""

    No results matching ""