Array 와 Event
• 차이점
- array 는 각 요소를 동기적 (sync) 으로 조회할 수 있고, 끝이 있다.
- event 는 각 요소를 비동기적 (async) 으로 조회할 수 있고, 끝이 없다.
(하지만 event listening 을 취소 할 수 있다.)
• 비동기적으로 생성되는 요소들을 표현하고, 원하는 시점에 취소할
수 있는 타입
13
Observable vs Promise
Promise Observable
single value multiple value
not lazy lazy
not cancelable cancelable
no completion callback completion callback
20
single value vs multiple value
• DOM / Event Emitter events (0 - N values)
• Animations (cancelable)
• REST API (1 value)
• WebSockets (0 - N values, retry)
• node.js core API (1 - N values)
21
single value vs multiple value
• DOM / Event Emitter events (0 - N values)
• Animations (cancelable)
• REST API (1 value)
• WebSockets (0 - N values)
• node.js core API (1 - N values)
22
Promise: not lazy
const p = new Promise(resolve => {
setTimeout(() => {
resolve(‘run');
}, 1000);
console.log('started');
});
23
Promise: not lazy
const p = new Promise(resolve => {
setTimeout(() => {
resolve(‘run');
}, 1000);
console.log('started');
});
24
executor
Promise: not lazy
const p = new Promise(resolve => {
setTimeout(() => {
resolve(‘run');
}, 1000);
console.log('started');
});
25 https://goo.gl/tK39aS
Promise: not lazy
const p = new Promise(resolve => {
setTimeout(() => {
resolve(‘run');
}, 1000);
console.log('started');
});
25
> "started"
https://goo.gl/tK39aS
Compose async with RxJS
• 여러 이벤트를 조합해야 할 때 (Drag & Drop)
• 다수의 비동기 함수를 조합하는 상황 (Cache or Db, AWS Lambda)
• 재시도가 필요한 경우 (on / offline)
77
Drag & Drop
• mousedown, mousemove, mouseup 3가지 유저 이벤트를 적절
하게 조합해야 함
- mousedown 이벤트가 발생하면 현재 엘리먼트의 초기 위치를 저장
- mousemove 이벤트가 발생하면 초기 위치 + 변한 위치를 계산해 새로운
위치로 엘리먼트를 옮김
- 언제까지? mouseup 이벤트가 발생할 때까지
78
Cache or DB
85
• cache 또는 DB 에서 데이터를 가져오는 상황
- getFromCache$(), getFromDB$()
- 둘 중에 먼저 도착한 데이터만 사용하고 싶다.
- 나머지 요청은 취소되어야 함
- getFromOtherServer$()
- 도착한 데이터의 값을 사용해 다른 요청 수행
Cache or Db
Rx.Observable.merge(getFromCache$(), getFromDB$())
.take(1)
.flatMap(data => getFromOtherServer$(data.id))
.subscribe(result => {
res.json(result)
}, err => {
res.status(500).send(err.message)
});
86
Cache or Db
Rx.Observable.merge(getFromCache$(), getFromDB$())
.take(1)
.flatMap(data => getFromOtherServer$(data.id))
.subscribe(result => {
res.json(result)
}, err => {
res.status(500).send(err.message)
});
87
Cache or Db
Rx.Observable.merge(getFromCache$(), getFromDB$())
.take(1)
.flatMap(data => getFromOtherServer$(data.id))
.subscribe(result => {
res.json(result)
}, err => {
res.status(500).send(err.message)
});
88
AWS Lambda
90
• Task function
- getTasks$()
- 태스크 큐에 쌓여있는 태스크 정보 가져오기
- checkNotified$()
- renderTaskCount$()
- 실패한 태스크가 존재하면 vega-renderer function 호출
• vega-renderer function
- upload$()
- 렌더링된 이미지를 s3 에 저장
- post$()
- 저장된 이미지 경로와 함께 슬랙에 알림 전송
Dan Abramov, @JavaScript Air 025
“Rx can solve many real world tasks.
And once you get used to it,
you can apply it pretty much everywhere.”
112
장점
• 데이터의 변환 / 흐름에만 집중 할 수 있다.
- 함수가 동기 / 비동기인지는 중요하지 않음
- Operator 는 마치 파이프 같음.
- 파이프(Operator)만 잘 연결하면, 물(데이터)은 파이프를 따라 흐른다.
- 이것이 Reactive Programming?
- 불가능하다고 생각했던 것들을 만들 수 있게 되었다.
• Observable 을 인터페이스의 중심으로
- Observable 은 거의 모든 비동기 상황을 표현할 수 있음.
- 쉬워진 새로운 기능 추가
- 쉬워진 테스트 (mocking 이 수월한 경우에...)
113
단점
• 러닝커브
- 커브 정도가 아니라 절벽 수준 😱
- 코드 + 사고방식까지 바꾸어야 함
- +200 Operators, Subject, Scheduler...
- 처음에는 무섭지만, 막상 사용하다보면 많이 사용하게 되는 건 7 ~ 8 개 정도?
• 디버깅
- 길고, 복잡한 call stack
• RxJS 의 내부 타입 / 구현을 모른다면 거의 쓸모없는 정보들 😥
• operator 를 제대로 이해하고 사용한다면 거의 볼 일이 없음
• RxJS@5 에서는 그나마 조금 줄었음
- do operator 를 활용하세요!!
• 서버 보다는 UI 개발에 더 많은 도움을 줄 수 있다고 생각함 🙏
114
Who to follow
• Erik Meijer
- creator of reactive-extensions
- 📹 One hacker way
• Matthew Podwyski
- initial creator of RxJS
• Ben Lesh
- RxJS@5 main contributor
115
• André Staltz
- RxJS@5 main contributor
- creator of cycle.js
• kris kowal
- creator of Q
- 📰 general theory of reactivity
What to see
• https://github.com/reactivex/rxjs
• 📰 official RxJS@5 doc
• 📹 💵 egghead RxJS series
- RxJS Beyond the Basics: Creating Observables from scratch
- RxJS Beyond the Basics: Operators in Depth
• 📖 learn-rxjs
116