startWith

signature: startWith(an: Values): Observable

주어진 값을 처음으로 방출합니다.

💡 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: scan한 값과 startWith사용하기

( 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'부터 시작하고, 이전값과 현재값 concat하기
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));

관련한 사용법

추가 자료

📂 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/startWith.ts

Last updated