RxJS는 Observable을 사용하여 비동기 및 이벤트 기반 프로그램을 작성하기 위한 라이브러리다.
// 보통
const eventHandler = event => {
console.log(event.currentTarget);
};
document.addEventListener('click', eventHandler);
// RxJS 적용
const { fromEvent } = rxjs;
const click$ = fromEvent(document, 'click'); // observable
const observer = event => console.log(event.currentTarget);
click$.subscribe(observer);
//개선 pluck 적용
const { pluck } = rxjs.operators;
const currentTarget$ = fromEvent(document, 'click').pipe(
pluck('currentTarget')
); // observable
const observer = target => console.log(target);
click$.subscribe(observer);
// 보통
const users = [
{
name: '유비',
birthYear: 161,
nationality: '촉'
},
{
name: '손권'
birthYear: 182,
nationality: '오'
},
{
name: '관우',
birthYear: 160,
nationality: '촉',
}
].filter(user => user.nationality === '촉');
const log = user => console.log(user);
users.forEach(log);
// RxJS
const { from } = rxjs;
const { filter } = rxjs.operators;
const users$ = from([
{
name: '유비',
birthYear: 161,
nationality: '촉'
},
{
name: '손권',
birthYear: 182,
nationality: '오'
},
{
name: '관우',
birthYear: 160,
nationality: '촉',
}
]).pipe(
filter(user => user.nationality === '촉')
);
const observer = user => console.log(user);
users$.subscribe(observer);
Observable
오퍼레이터
Observer
// Observer 객체를 전달하는 subscribe
const observer = {
next: value => console.log(value),
error: error => console.error(error),
complete: () => console.log('complete'),
};
// next 콜백 함수를 전달하는 subscribe
click$.subscribe(value => console.log(value));
// next, error, complete 콜백 함수를 전달
click$.subscribe(
value => console.log(value),
err => console.error(error),
() => console.log('complete')
);
Subscription
const subscription = currentTarget$.subscribe(observer);
subscription.unsubscribe();