Javascript/Rxjs

Rxjs기능 Create, from, fromEvent

마샤와 곰 2019. 5. 13. 17:19

 

 

직관적인 기능이다. 말 그대로 관측하는 대상을 만들어 준다.

import { Observable } from 'rxjs';

const hello = Observable.create(function(observer) {
  observer.next('123');
  observer.next('456');
  observer.complete();  //행위 종료선언
});

const subscribe = hello.subscribe(val => console.log(val));  //123 456이 출력된다

complete를 통해서 구독을 멈추는 기능을 보았다. complete를 하지 않으면 구독행위는 중단되지 않는다.

 

from은 ~부터의 의미로 데이터가 등록된 이후로의 행위를 정의한다.

import { from } from 'rxjs';

const array = from([1, 2, 3, 4, 5]);
const subscribe = array.subscribe(val => console.log(val));  //1~5까지 출력


const text = from('Hello World');
const subscribe2 = text.subscribe(val => console.log(val)); //hello world가 1개씩 출력된다.

const map = new Map();
map.set(1, '가나다');
map.set(2, '1234');

const mapSource = from(map);
const sub2 = mapSource.subscribe(val => console.log(val)); //맵 객체가 1개씩 출력된다.

이벤트를 통한 감시(구독)행위도 가능하다.

import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';

const source = fromEvent(document, 'click');  //document는 문서 그 자체이다. 원하는 객체를 선언해도 된다.
const subscribe = source.subscribe(val => console.log(val));//해당 이벤트 발생행위에 대한 콜백을 써주자.

 

반응형