Skip to content

Instantly share code, notes, and snippets.

@kyungmi
Last active November 18, 2018 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyungmi/17dcce70ad1ca140ff93d0c6bc677fe3 to your computer and use it in GitHub Desktop.
Save kyungmi/17dcce70ad1ca140ff93d0c6bc677fe3 to your computer and use it in GitHub Desktop.
RxJS 퀵스타트 9장
const drag$ = start$.pipe(
switchMap(start => move$.pipe(
// 처음 X 좌표에서 이동한 거리를 반환
map(move => ({ distance: move - start })),
takeUntil(end$),
)),
share(),
);
const drop$ = drag$.pipe(
switchMap(drag => end$.pipe(
map(() => drag),
first(),
)),
withLatestFrom(viewWidth$, (drag, size) => ({ ...drag, size })),
);
// {distance: 353, size: 1023}
const { merge } = rxjs;
const THRESHOLD = 30;
const PANEL_COUNT = 5;
const carousel$ = merge(drag$, drop$).pipe(
scan((store, { distance, size } ) => {
let updateStore = { from: -(store.index * store.size) + distance };
if (size === undefined) {
// drag
updateStore = { ...updatStore, to: updateStore.from };
} else {
// drop
let toBeIndex = store.index;
if (Math.abs(distance) >= THRESHOLD) {
toBeIndex = distance < 0 ? Math.min(toBeIndex + 1, PANEL_COUNT - 1) : Math.max(toBeIndex - 1, 0);
}
updateStore = { ...updateStore, index: toBeIndex, to: -(toBeIndex * size), size };
}
return { ...store, ...updateStore };
}, { from: 0, to: 0, index: 0, size: 0 }),
);
carousel$.subscribe(v => console.log('캐러셀 데이터', v));
// 캐러셀 데이터 {from: 0, to: 0, index: 0, size: 1023}
// 캐러셀 데이터 {from: -1, to: -1, index: 0, size: 1023}
// 캐러셀 데이터 {from: -8, to: -8, index: 0, size: 1023}
// 캐러셀 데이터 {from: -64, to: -64, index: 0, size: 1023}
// 캐러셀 데이터 {from: -142, to: -142, index: 0, size: 1023}
// 캐러셀 데이터 {from: -236, to: -236, index: 0, size: 1023}
// 캐러셀 데이터 {from: -270, to: -270, index: 0, size: 1023}
// 캐러셀 데이터 {from: -270, to: -1023, index: 1, size: 1023} // drop 시점
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment