์ฝ˜ํ…์ธ  ๋Œ€ํ‘œ ์ด๋ฏธ์ง€ - ๐ŸŒŠ RxJS์™€ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ: ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ตฌํ˜„
TypeScript ร— RxJS

๐ŸŒŠ RxJS์™€ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ: ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ตฌํ˜„

๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ์„ ์ž์œ ์ž์žฌ๋กœ ๋‹ค๋ฃจ๋Š” ๋ฆฌ์•กํ‹ฐ๋ธŒ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ์„ธ๊ณ„๋กœ ๐Ÿš€

๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๋ฐ์ดํ„ฐ ํ๋ฆ„ ์ด๋ฒคํŠธ ์†Œ์Šค ํด๋ฆญ, HTTP, ํƒ€์ด๋จธ Observable ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ ์ƒ์„ฑ Operators map, filter, merge... Observer ๊ตฌ๋… & ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ UI ๋ฐ˜์˜ ๐Ÿ“ก ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ ํ๋ฆ„ โ‘  โ‘ก โ‘ข โ‘ฃ โ‘ค โœ“ ์ด๋ฒคํŠธ๋ฐœ์ƒ ์ŠคํŠธ๋ฆผ์ƒ์„ฑ ํ•„ํ„ฐ๋ง ๋ณ€ํ™˜ ๊ตฌ๋… ์™„๋ฃŒ TypeScript ํƒ€์ž… ์•ˆ์ „์„ฑ ๋ณด์žฅ RxJS ๋ฐ˜์‘ํ˜• ํ™•์žฅ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ RxJS + TypeScript ํƒ€์ž… ์•ˆ์ „ํ•œ ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๐ŸŽฏ
๐Ÿค” ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ, ๋„๋Œ€์ฒด ๋ญ”๋ฐ?

์†”์งํžˆ ๋งํ•˜๋ฉด, ์ฒ˜์Œ "๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ(Reactive Programming)"์ด๋ผ๋Š” ๋ง์„ ๋“ค์—ˆ์„ ๋•Œ ๋ญ”๊ฐ€ ์—„์ฒญ ๋ณต์žกํ•œ ๊ฐœ๋… ๊ฐ™์•„์„œ ์ง€๋ ˆ ๊ฒ๋จน๋Š” ๋ถ„๋“ค์ด ๋งŽ์•„์š”. ๊ทผ๋ฐ ์‚ฌ์‹ค ๊ฐœ๋… ์ž์ฒด๋Š” ์ƒ๊ฐ๋ณด๋‹ค ์ง๊ด€์ ์ด์—์š”! ๐Ÿ™Œ

์‰ฝ๊ฒŒ ์„ค๋ช…ํ•˜๋ฉด ์ด๋ ‡์Šต๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๊ฐ€ ์ผ๋ฐ˜์ ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์งค ๋•Œ๋Š” "์ด ๊ฐ’์„ ๊ฐ€์ ธ์™€์„œ, ์ฒ˜๋ฆฌํ•˜๊ณ , ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด" ๊ฐ™์€ ๋ช…๋ นํ˜• ๋ฐฉ์‹์„ ์จ์š”. ๋ฐ˜๋ฉด ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์€ "์ด ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ์„ ๊ตฌ๋…ํ•˜๊ณ  ์žˆ๋‹ค๊ฐ€, ๋ญ”๊ฐ€ ํ˜๋Ÿฌ์˜ค๋ฉด ๊ทธ๋•Œ ์ฒ˜๋ฆฌํ•ด" ๋ผ๋Š” ๋ฐฉ์‹์ด์—์š”.

๐Ÿ’ก ํ•ต์‹ฌ ๊ฐœ๋…: ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์€ ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ(Data Stream)๊ณผ ๋ณ€ํ™”์˜ ์ „ํŒŒ(Propagation of Change)๋ฅผ ์ค‘์‹ฌ์œผ๋กœ ํ•˜๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํŒจ๋Ÿฌ๋‹ค์ž„์ž…๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด๋ณผ๊ฒŒ์š”. ์—‘์…€ ์Šคํ”„๋ ˆ๋“œ์‹œํŠธ ์ƒ๊ฐํ•ด๋ณด์„ธ์š”. A1 ์…€์— ์ˆซ์ž๋ฅผ ๋„ฃ๊ณ , B1 ์…€์— =A1*2 ๋ผ๊ณ  ์ž…๋ ฅํ•˜๋ฉด, A1 ๊ฐ’์ด ๋ฐ”๋€” ๋•Œ๋งˆ๋‹ค B1๋„ ์ž๋™์œผ๋กœ ๋ฐ”๋€Œ์ž–์•„์š”? ์ด๊ฒŒ ๋ฐ”๋กœ ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ํ•ต์‹ฌ ์•„์ด๋””์–ด์˜ˆ์š”! ๐ŸŽฏ

์›น ๊ฐœ๋ฐœ์—์„œ๋Š” ์ด๋Ÿฐ ์ƒํ™ฉ๋“ค์ด ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ๊ณผ ๋”ฑ ๋งž์•„์š”:

๐Ÿ–ฑ๏ธ ์‚ฌ์šฉ์ž ์ด๋ฒคํŠธ
ํด๋ฆญ, ํ‚ค๋ณด๋“œ ์ž…๋ ฅ, ๋งˆ์šฐ์Šค ์›€์ง์ž„ ๋“ฑ ์—ฐ์†์ ์œผ๋กœ ๋ฐœ์ƒํ•˜๋Š” ์ด๋ฒคํŠธ๋“ค
๐ŸŒ HTTP ์š”์ฒญ
๋น„๋™๊ธฐ API ํ˜ธ์ถœ, ์‹ค์‹œ๊ฐ„ ๋ฐ์ดํ„ฐ ํด๋ง, WebSocket ์—ฐ๊ฒฐ
โฑ๏ธ ํƒ€์ด๋จธ/์ธํ„ฐ๋ฒŒ
์ฃผ๊ธฐ์ ์œผ๋กœ ๋ฐœ์ƒํ•˜๋Š” ์ด๋ฒคํŠธ, ์• ๋‹ˆ๋ฉ”์ด์…˜ ํ”„๋ ˆ์ž„
๋ช…๋ นํ˜• vs ๋ฐ˜์‘ํ˜•: ์‹ค์ œ ์ฐจ์ด์ 

๊ฒ€์ƒ‰์ฐฝ์— ํƒ€์ดํ•‘ํ•  ๋•Œ๋งˆ๋‹ค API๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ด์š”. ๋ช…๋ นํ˜•์œผ๋กœ ์งœ๋ฉด ์ด๋ ‡๊ฒŒ ๋ฉ๋‹ˆ๋‹ค:

โŒ ๋ช…๋ นํ˜• ๋ฐฉ์‹ (๋ฌธ์ œ ์žˆ์Œ)
// ํƒ€์ดํ•‘ํ•  ๋•Œ๋งˆ๋‹ค API ํ˜ธ์ถœ โ†’ ๊ณผ๋ถ€ํ•˜ ๋ฐœ์ƒ!
inputElement.addEventListener('input', (event) => {
  const query = event.target.value;
  fetch(`/api/search?q=${query}`)
    .then(res => res.json())
    .then(data => renderResults(data));
});
// ๋ฌธ์ œ: ํƒ€์ดํ•‘ ์†๋„๋งŒํผ API ํ˜ธ์ถœ๋จ, ์ด์ „ ์š”์ฒญ ์ทจ์†Œ ๋ถˆ๊ฐ€, ์ˆœ์„œ ๋ณด์žฅ ์•ˆ๋จ
โœ… ๋ฐ˜์‘ํ˜• ๋ฐฉ์‹ (RxJS)
import { fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

fromEvent(inputElement, 'input').pipe(
  debounceTime(300),        // 300ms ๋™์•ˆ ์ž…๋ ฅ ์—†์œผ๋ฉด ์‹คํ–‰
  distinctUntilChanged(),   // ์ด์ „ ๊ฐ’๊ณผ ๊ฐ™์œผ๋ฉด ๋ฌด์‹œ
  switchMap(event => fetch(`/api/search?q=${event.target.value}`))
).subscribe(data => renderResults(data));
// ๊น”๋”ํ•˜๊ณ , ์ž๋™์œผ๋กœ ์ด์ „ ์š”์ฒญ ์ทจ์†Œ, ์ˆœ์„œ ๋ณด์žฅ!

์–ด๋•Œ์š”? ๋ฐ˜์‘ํ˜• ๋ฐฉ์‹์ด ํ›จ์”ฌ ์„ ์–ธ์ ์ด๊ณ  ์ฝ๊ธฐ ์‰ฝ์ฃ ? ๐ŸŽ‰ ์ด๊ฒŒ RxJS์˜ ๋งค๋ ฅ์ด์—์š”.


๐Ÿ“š RxJS ํ•ต์‹ฌ ๊ฐœ๋… ์™„์ „ ์ •๋ณต

RxJS(Reactive Extensions for JavaScript)๋Š” ๋งˆ์ดํฌ๋กœ์†Œํ”„ํŠธ๊ฐ€ ๋งŒ๋“  ReactiveX ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ JavaScript ๋ฒ„์ „์ด์—์š”. ํ˜„์žฌ ๋ฒ„์ „ 7.x๊ฐ€ ์•ˆ์ • ๋ฒ„์ „์ด๊ณ , Angular ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ๋Š” ๊ธฐ๋ณธ์œผ๋กœ ํƒ‘์žฌ๋˜์–ด ์žˆ์„ ๋งŒํผ ์‹ค๋ฌด์—์„œ ๋งŽ์ด ์“ฐ์ด๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ˆ์š”.

๐Ÿ”ต Observable: ์ŠคํŠธ๋ฆผ์˜ ์‹œ์ž‘์ 

Observable์€ RxJS์˜ ํ•ต์‹ฌ ์ค‘์˜ ํ•ต์‹ฌ์ด์—์š”. ์‹œ๊ฐ„์ด ์ง€๋‚จ์— ๋”ฐ๋ผ ์—ฌ๋Ÿฌ ๊ฐ’์„ ๋ฐฉ์ถœ(emit)ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒŒ์œผ๋ฅธ(lazy) ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋ผ์š”.

๐ŸŽฏ Observable์€ ๊ตฌ๋…(subscribe)ํ•˜๊ธฐ ์ „๊นŒ์ง€๋Š” ์•„๋ฌด๊ฒƒ๋„ ์‹คํ–‰๋˜์ง€ ์•Š์•„์š”! ์ด๊ฒŒ "๊ฒŒ์œผ๋ฅด๋‹ค(lazy)"๋Š” ์˜๋ฏธ์˜ˆ์š”. Promise์™€ ๋‹ค๋ฅด๊ฒŒ, ๊ตฌ๋…์ž๊ฐ€ ์—†์œผ๋ฉด ์•„๋ฌด ์ผ๋„ ์•ˆ ์ผ์–ด๋‚ฉ๋‹ˆ๋‹ค.
Observable ๊ธฐ๋ณธ ์ƒ์„ฑ
import { Observable } from 'rxjs';

// Observable ์ง์ ‘ ์ƒ์„ฑ
const myObservable = new Observable(subscriber => {
  subscriber.next(1);    // ๊ฐ’ ๋ฐฉ์ถœ
  subscriber.next(2);    // ๊ฐ’ ๋ฐฉ์ถœ
  subscriber.next(3);    // ๊ฐ’ ๋ฐฉ์ถœ
  subscriber.complete(); // ์™„๋ฃŒ ์‹ ํ˜ธ
});

// ๊ตฌ๋…ํ•ด์•ผ ์‹คํ–‰๋จ!
myObservable.subscribe({
  next: (value) => console.log('๋ฐ›์€ ๊ฐ’:', value),
  error: (err) => console.error('์—๋Ÿฌ:', err),
  complete: () => console.log('์™„๋ฃŒ!')
});
// ์ถœ๋ ฅ: ๋ฐ›์€ ๊ฐ’: 1, ๋ฐ›์€ ๊ฐ’: 2, ๋ฐ›์€ ๊ฐ’: 3, ์™„๋ฃŒ!
๐ŸŸข Observer: ์ŠคํŠธ๋ฆผ์„ ๋ฐ›๋Š” ์ชฝ

Observer๋Š” Observable์ด ๋ฐฉ์ถœํ•˜๋Š” ๊ฐ’์„ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฐ์ฒด์˜ˆ์š”. ์„ธ ๊ฐ€์ง€ ์ฝœ๋ฐฑ์œผ๋กœ ๊ตฌ์„ฑ๋ฉ๋‹ˆ๋‹ค:

์ฝœ๋ฐฑ ์—ญํ•  ํ˜ธ์ถœ ์‹œ์ 
next ์ •์ƒ ๊ฐ’ ์ฒ˜๋ฆฌ Observable์ด ๊ฐ’์„ ๋ฐฉ์ถœํ•  ๋•Œ๋งˆ๋‹ค
error ์—๋Ÿฌ ์ฒ˜๋ฆฌ ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ (์ดํ›„ ์ŠคํŠธ๋ฆผ ์ข…๋ฃŒ)
complete ์™„๋ฃŒ ์ฒ˜๋ฆฌ ์ŠคํŠธ๋ฆผ์ด ์ •์ƒ ์ข…๋ฃŒ๋  ๋•Œ
๐Ÿ”ด Subject: Observable์ด์ž Observer

Subject๋Š” RxJS์—์„œ ํŠน๋ณ„ํ•œ ์กด์žฌ์˜ˆ์š”. Observable์ด๋ฉด์„œ ๋™์‹œ์— Observer์ด๊ธฐ๋„ ํ•ด์š”. ์ฆ‰, ๊ฐ’์„ ๋ฐฉ์ถœํ•  ์ˆ˜๋„ ์žˆ๊ณ , ๋‹ค๋ฅธ Observable์„ ๊ตฌ๋…ํ•  ์ˆ˜๋„ ์žˆ์–ด์š”. ๋ฉ€ํ‹ฐ์บ์ŠคํŒ…(์—ฌ๋Ÿฌ ๊ตฌ๋…์ž์—๊ฒŒ ๋™์‹œ์— ๊ฐ’ ์ „๋‹ฌ)์ด ๊ฐ€๋Šฅํ•œ ๊ฒŒ ํ•ต์‹ฌ ํŠน์ง•์ด์—์š”!

Subject ์‚ฌ์šฉ ์˜ˆ์‹œ
import { Subject } from 'rxjs';

const subject = new Subject<number>();

// ๊ตฌ๋…์ž 1
subject.subscribe(val => console.log('๊ตฌ๋…์ž1:', val));

// ๊ตฌ๋…์ž 2
subject.subscribe(val => console.log('๊ตฌ๋…์ž2:', val));

// ๊ฐ’ ๋ฐฉ์ถœ (๋‘ ๊ตฌ๋…์ž ๋ชจ๋‘ ๋ฐ›์Œ)
subject.next(1); // ๊ตฌ๋…์ž1: 1, ๊ตฌ๋…์ž2: 1
subject.next(2); // ๊ตฌ๋…์ž1: 2, ๊ตฌ๋…์ž2: 2
Subject์˜ ์ข…๋ฅ˜๋“ค
BehaviorSubject
์ดˆ๊ธฐ๊ฐ’์„ ๊ฐ€์ง€๋ฉฐ, ์ƒˆ ๊ตฌ๋…์ž์—๊ฒŒ ๋งˆ์ง€๋ง‰ ๊ฐ’์„ ์ฆ‰์‹œ ์ „๋‹ฌ. ์ƒํƒœ ๊ด€๋ฆฌ์— ์ตœ์ !
ReplaySubject
์ง€์ •ํ•œ ๊ฐœ์ˆ˜๋งŒํผ ์ด์ „ ๊ฐ’๋“ค์„ ๋ฒ„ํผ๋งํ•ด์„œ ์ƒˆ ๊ตฌ๋…์ž์—๊ฒŒ ์žฌ์ „์†ก
AsyncSubject
complete() ํ˜ธ์ถœ ์‹œ ๋งˆ์ง€๋ง‰ ๊ฐ’๋งŒ ๊ตฌ๋…์ž์—๊ฒŒ ์ „๋‹ฌ
๐Ÿ”— Subscription: ๊ตฌ๋… ๊ด€๋ฆฌ

subscribe()๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด Subscription ๊ฐ์ฒด๊ฐ€ ๋ฐ˜ํ™˜๋ผ์š”. ์ด๊ฑธ ํ†ตํ•ด ๊ตฌ๋…์„ ํ•ด์ œ(unsubscribe)ํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ๋ฐฉ์ง€๋ฅผ ์œ„ํ•ด ๋ฐ˜๋“œ์‹œ ๊ตฌ๋… ํ•ด์ œ๋ฅผ ํ•ด์ค˜์•ผ ํ•ด์š”! ํŠนํžˆ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์†Œ๋ฉธ๋  ๋•Œ์š”.

๊ตฌ๋… ํ•ด์ œ ํŒจํ„ด
import { interval } from 'rxjs';

const subscription = interval(1000).subscribe(val => {
  console.log('๋งค์ดˆ๋งˆ๋‹ค:', val);
});

// 5์ดˆ ํ›„ ๊ตฌ๋… ํ•ด์ œ
setTimeout(() => {
  subscription.unsubscribe();
  console.log('๊ตฌ๋… ํ•ด์ œ๋จ!');
}, 5000);

๐Ÿ’™ TypeScript์™€ RxJS: ์ตœ๊ฐ•์˜ ์กฐํ•ฉ

RxJS ์ž์ฒด๋„ ํ›Œ๋ฅญํ•˜์ง€๋งŒ, TypeScript์™€ ํ•จ๊ป˜ ์“ฐ๋ฉด ์ง„์งœ ๋‚ ๊ฐœ๋ฅผ ๋‹ฌ์•„์š”! ๐Ÿฆ… ํƒ€์ž… ์•ˆ์ „์„ฑ์ด ๋ณด์žฅ๋˜๋‹ˆ๊นŒ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๋ฅผ ์ปดํŒŒ์ผ ํƒ€์ž„์— ์žก์„ ์ˆ˜ ์žˆ๊ฑฐ๋“ ์š”.

์ œ๋„ค๋ฆญ์œผ๋กœ ํƒ€์ž… ์•ˆ์ „ํ•œ Observable
TypeScript + RxJS ํƒ€์ž… ์ง€์ •
import { Observable, of, from } from 'rxjs';
import { map, filter } from 'rxjs/operators';

// ์ธํ„ฐํŽ˜์ด์Šค ์ •์˜
interface User {
  id: number;
  name: string;
  age: number;
  email: string;
}

// ํƒ€์ž…์ด ๋ช…ํ™•ํ•œ Observable
const users$: Observable<User[]> = of([
  { id: 1, name: '๊น€์ฒ ์ˆ˜', age: 25, email: 'kim@example.com' },
  { id: 2, name: '์ด์˜ํฌ', age: 30, email: 'lee@example.com' },
  { id: 3, name: '๋ฐ•๋ฏผ์ค€', age: 17, email: 'park@example.com' },
]);

// ํƒ€์ž… ์ถ”๋ก ์ด ์™„๋ฒฝํ•˜๊ฒŒ ๋™์ž‘!
const adultUsers$ = users$.pipe(
  map(users => users.filter(user => user.age >= 18)),
  // ์—ฌ๊ธฐ์„œ users๋Š” User[] ํƒ€์ž…์œผ๋กœ ์ž๋™ ์ถ”๋ก ๋จ
);

adultUsers$.subscribe((users: User[]) => {
  users.forEach(user => console.log(user.name)); // ํƒ€์ž… ์•ˆ์ „!
});
์ปค์Šคํ…€ ํƒ€์ž…์œผ๋กœ API ์‘๋‹ต ์ฒ˜๋ฆฌ
์‹ค๋ฌด ํŒจํ„ด: HTTP ์š”์ฒญ ํƒ€์ž… ์•ˆ์ „ํ•˜๊ฒŒ ์ฒ˜๋ฆฌ
import { Observable, throwError } from 'rxjs';
import { catchError, map, retry } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

// API ์‘๋‹ต ํƒ€์ž… ์ •์˜
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

interface Product {
  id: number;
  name: string;
  price: number;
  category: string;
}

// ์ œ๋„ค๋ฆญ HTTP ์„œ๋น„์Šค ํ•จ์ˆ˜
function fetchData<T>(url: string): Observable<T> {
  return ajax.getJSON<ApiResponse<T>>(url).pipe(
    map(response => response.data),
    retry(3), // ์‹คํŒจ ์‹œ 3๋ฒˆ ์žฌ์‹œ๋„
    catchError(error => {
      console.error('API ์—๋Ÿฌ:', error);
      return throwError(() => new Error('๋ฐ์ดํ„ฐ ๋กœ๋“œ ์‹คํŒจ'));
    })
  );
}

// ์‚ฌ์šฉ ์‹œ ํƒ€์ž… ์ถ”๋ก  ์™„๋ฒฝ!
const products$ = fetchData<Product[]>('/api/products');
products$.subscribe(products => {
  // products๋Š” Product[] ํƒ€์ž…์œผ๋กœ ์ž๋™ ์ถ”๋ก 
  products.forEach(p => console.log(`${p.name}: ${p.price}์›`));
});
๐Ÿ’š ํŒ: Observable ๋ณ€์ˆ˜๋ช… ๋’ค์— $๋ฅผ ๋ถ™์ด๋Š” ๊ฑด RxJS ์ปค๋ฎค๋‹ˆํ‹ฐ์˜ ๊ด€๋ก€์˜ˆ์š”. users$, products$ ์ฒ˜๋Ÿผ์š”. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ฝ”๋“œ์—์„œ Observable์ธ์ง€ ์ผ๋ฐ˜ ๋ณ€์ˆ˜์ธ์ง€ ํ•œ๋ˆˆ์— ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์žˆ์–ด์š”!
ํƒ€์ž… ๊ฐ€๋“œ์™€ RxJS ๊ฒฐํ•ฉ
ํƒ€์ž… ๊ฐ€๋“œ ํ™œ์šฉ
import { Observable, of } from 'rxjs';
import { filter } from 'rxjs/operators';

type ApiResult = User | null | undefined;

// ํƒ€์ž… ๊ฐ€๋“œ ํ•จ์ˆ˜
function isUser(value: ApiResult): value is User {
  return value !== null && value !== undefined && 'id' in value;
}

const result$: Observable<ApiResult> = of(
  { id: 1, name: '๊น€์ฒ ์ˆ˜', age: 25, email: 'kim@example.com' },
  null,
  undefined,
  { id: 2, name: '์ด์˜ํฌ', age: 30, email: 'lee@example.com' }
);

// filter์— ํƒ€์ž… ๊ฐ€๋“œ ์ ์šฉ โ†’ ํƒ€์ž…์ด User๋กœ ์ขํ˜€์ง!
const validUsers$ = result$.pipe(
  filter(isUser) // ์ดํ›„ ํƒ€์ž…์€ Observable<User>
);

validUsers$.subscribe(user => {
  console.log(user.name); // TypeScript๊ฐ€ user๋ฅผ User๋กœ ์ธ์‹!
});
๐Ÿ”ง RxJS ์ฃผ์š” ์˜คํผ๋ ˆ์ดํ„ฐ ๋ถ„๋ฅ˜ ๐Ÿ”„ ๋ณ€ํ™˜ map switchMap mergeMap concatMap exhaustMap scan reduce pluck mapTo ๐Ÿ” ํ•„ํ„ฐ๋ง filter take takeUntil skip debounceTime throttleTime distinctUntilChanged first last ๐Ÿ”— ๊ฒฐํ•ฉ merge concat combineLatest zip forkJoin withLatestFrom race startWith ๐Ÿ› ๏ธ ์œ ํ‹ธ๋ฆฌํ‹ฐ tap catchError retry retryWhen delay timeout share shareReplay finalize pipe() ๋ฉ”์„œ๋“œ๋กœ ์ฒด์ด๋‹ํ•˜์—ฌ ์‚ฌ์šฉ ๐Ÿ”—

โšก ํ•ต์‹ฌ ์˜คํผ๋ ˆ์ดํ„ฐ ์™„์ „ ์ •๋ณต

RxJS์—๋Š” 100๊ฐœ๊ฐ€ ๋„˜๋Š” ์˜คํผ๋ ˆ์ดํ„ฐ๊ฐ€ ์žˆ๋Š”๋ฐ, ์ฒ˜์Œ๋ถ€ํ„ฐ ๋‹ค ์™ธ์šฐ๋ ค๊ณ  ํ•˜๋ฉด ๋จธ๋ฆฌ๊ฐ€ ํ„ฐ์ ธ์š” ๐Ÿ’ฅ. ์‹ค๋ฌด์—์„œ ์ž์ฃผ ์“ฐ์ด๋Š” ํ•ต์‹ฌ ์˜คํผ๋ ˆ์ดํ„ฐ๋“ค๋งŒ ์ œ๋Œ€๋กœ ์ดํ•ดํ•˜๋ฉด ์ถฉ๋ถ„ํ•ด์š”!

๐Ÿ—บ๏ธ map: ๊ฐ’ ๋ณ€ํ™˜์˜ ๊ธฐ๋ณธ

๋ฐฐ์—ด์˜ map๊ณผ ๋˜‘๊ฐ™์€ ๊ฐœ๋…์ด์—์š”. ์ŠคํŠธ๋ฆผ์˜ ๊ฐ ๊ฐ’์„ ๋‹ค๋ฅธ ๊ฐ’์œผ๋กœ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

map ์˜คํผ๋ ˆ์ดํ„ฐ
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

// ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜
of(1, 2, 3, 4, 5).pipe(
  map(num => `${num}๋ฒˆ์งธ ์•„์ดํ…œ`)
).subscribe(console.log);
// "1๋ฒˆ์งธ ์•„์ดํ…œ", "2๋ฒˆ์งธ ์•„์ดํ…œ", ...

// ๊ฐ์ฒด ๋ณ€ํ™˜
interface RawUser { id: number; full_name: string; }
interface User { id: number; name: string; }

const rawUser$: Observable<RawUser> = of({ id: 1, full_name: '๊น€์ฒ ์ˆ˜' });
const user$: Observable<User> = rawUser$.pipe(
  map(raw => ({ id: raw.id, name: raw.full_name }))
);
๐Ÿ”€ switchMap vs mergeMap vs concatMap vs exhaustMap

์ด ๋„ค ๊ฐ€์ง€๋Š” RxJS์—์„œ ๊ฐ€์žฅ ํ—ท๊ฐˆ๋ฆฌ๋Š” ์˜คํผ๋ ˆ์ดํ„ฐ๋“ค์ด์—์š”. ๋ชจ๋‘ "Observable์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜"๋ฅผ ์ธ์ž๋กœ ๋ฐ›๋Š”๋ฐ, ๋™์ž‘ ๋ฐฉ์‹์ด ๋‹ฌ๋ผ์š”!

์˜คํผ๋ ˆ์ดํ„ฐ ์ƒˆ ์š”์ฒญ ์™”์„ ๋•Œ ์ฃผ์š” ์‚ฌ์šฉ ์‚ฌ๋ก€
switchMap ์ด์ „ ์š”์ฒญ ์ทจ์†Œ, ์ƒˆ ์š”์ฒญ ์‹คํ–‰ ๊ฒ€์ƒ‰ ์ž๋™์™„์„ฑ, ์ตœ์‹  ๊ฐ’๋งŒ ํ•„์š”ํ•  ๋•Œ
mergeMap ์ด์ „ ์š”์ฒญ ์œ ์ง€, ๋ณ‘๋ ฌ ์‹คํ–‰ ๋…๋ฆฝ์ ์ธ ๋ณ‘๋ ฌ ์š”์ฒญ, ์ˆœ์„œ ๋ฌด๊ด€
concatMap ์ด์ „ ์š”์ฒญ ์™„๋ฃŒ ํ›„ ์ˆœ์„œ๋Œ€๋กœ ์‹คํ–‰ ์ˆœ์„œ๊ฐ€ ์ค‘์š”ํ•œ ์ž‘์—…, ํŒŒ์ผ ์—…๋กœ๋“œ
exhaustMap ์ด์ „ ์š”์ฒญ ์ง„ํ–‰ ์ค‘์ด๋ฉด ์ƒˆ ์š”์ฒญ ๋ฌด์‹œ ๋กœ๊ทธ์ธ ๋ฒ„ํŠผ, ์ค‘๋ณต ์ œ์ถœ ๋ฐฉ์ง€
switchMap ์‹ค์ „ ์˜ˆ์‹œ (๊ฒ€์ƒ‰ ์ž๋™์™„์„ฑ)
import { fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, map } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

interface SearchResult {
  id: number;
  title: string;
}

const searchInput = document.getElementById('search') as HTMLInputElement;

fromEvent<InputEvent>(searchInput, 'input').pipe(
  map(event => (event.target as HTMLInputElement).value),
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(query => 
    ajax.getJSON<SearchResult[]>(`/api/search?q=${query}`)
  )
).subscribe(results => {
  console.log('๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ:', results);
  // ์ด์ „ ๊ฒ€์ƒ‰ ์š”์ฒญ์€ ์ž๋™์œผ๋กœ ์ทจ์†Œ๋จ!
});
exhaustMap ์‹ค์ „ ์˜ˆ์‹œ (๋กœ๊ทธ์ธ ๋ฒ„ํŠผ)
import { fromEvent } from 'rxjs';
import { exhaustMap, tap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

interface LoginPayload { username: string; password: string; }
interface LoginResponse { token: string; user: User; }

const loginBtn = document.getElementById('login-btn') as HTMLButtonElement;

fromEvent(loginBtn, 'click').pipe(
  exhaustMap(() => {
    const payload: LoginPayload = {
      username: 'user@example.com',
      password: 'password123'
    };
    return ajax.post<LoginResponse>('/api/login', payload);
  }),
  tap(() => loginBtn.disabled = true)
).subscribe({
  next: response => {
    localStorage.setItem('token', response.response.token);
    window.location.href = '/dashboard';
  },
  error: err => console.error('๋กœ๊ทธ์ธ ์‹คํŒจ:', err)
});
// ๋กœ๊ทธ์ธ ์š”์ฒญ ์ค‘์— ๋ฒ„ํŠผ์„ ์•„๋ฌด๋ฆฌ ๋ˆŒ๋Ÿฌ๋„ ์ค‘๋ณต ์š”์ฒญ ์•ˆ ๋จ!
๐Ÿ”— combineLatest: ์—ฌ๋Ÿฌ ์ŠคํŠธ๋ฆผ ๊ฒฐํ•ฉ

์—ฌ๋Ÿฌ Observable์˜ ์ตœ์‹  ๊ฐ’์„ ๊ฒฐํ•ฉํ•  ๋•Œ ์‚ฌ์šฉํ•ด์š”. ๋ชจ๋“  Observable์ด ์ตœ์†Œ ํ•œ ๋ฒˆ์”ฉ ๊ฐ’์„ ๋ฐฉ์ถœํ•œ ํ›„๋ถ€ํ„ฐ ๋™์ž‘ํ•ด์š”.

combineLatest ์˜ˆ์‹œ
import { combineLatest, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

// ํ•„ํ„ฐ ์ƒํƒœ ๊ด€๋ฆฌ
const category$ = new BehaviorSubject<string>('all');
const priceRange$ = new BehaviorSubject<[number, number]>([0, 100000]);
const sortBy$ = new BehaviorSubject<string>('price');

// ์„ธ ๊ฐ€์ง€ ํ•„ํ„ฐ๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ์ž๋™์œผ๋กœ ์ƒˆ ํ•„ํ„ฐ ์กฐ๊ฑด ์ƒ์„ฑ
const filterConfig$ = combineLatest([category$, priceRange$, sortBy$]).pipe(
  map(([category, [minPrice, maxPrice], sortBy]) => ({
    category,
    minPrice,
    maxPrice,
    sortBy
  }))
);

filterConfig$.subscribe(config => {
  console.log('ํ•„ํ„ฐ ๋ณ€๊ฒฝ:', config);
  // API ์žฌํ˜ธ์ถœ ๋˜๋Š” ๋กœ์ปฌ ํ•„ํ„ฐ๋ง
  fetchProducts(config);
});

// ์นดํ…Œ๊ณ ๋ฆฌ ๋ณ€๊ฒฝ โ†’ ์ž๋™์œผ๋กœ filterConfig$ ์—…๋ฐ์ดํŠธ
category$.next('electronics');
๐Ÿ” forkJoin: ์—ฌ๋Ÿฌ ์š”์ฒญ ๋™์‹œ ์‹คํ–‰ ํ›„ ๋ชจ๋‘ ์™„๋ฃŒ ๋Œ€๊ธฐ

Promise.all()๊ณผ ๋น„์Šทํ•œ ๊ฐœ๋…์ด์—์š”. ์—ฌ๋Ÿฌ Observable์ด ๋ชจ๋‘ ์™„๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ ธ๋‹ค๊ฐ€ ๋งˆ์ง€๋ง‰ ๊ฐ’๋“ค์„ ํ•œ ๋ฒˆ์— ๋ฐฉ์ถœํ•ด์š”.

forkJoin ์˜ˆ์‹œ
import { forkJoin } from 'rxjs';
import { ajax } from 'rxjs/ajax';

interface UserProfile { id: number; name: string; }
interface UserPosts { posts: Post[]; }
interface UserFollowers { followers: User[]; }

// ์„ธ API๋ฅผ ๋™์‹œ์— ํ˜ธ์ถœํ•˜๊ณ  ๋ชจ๋‘ ์™„๋ฃŒ๋˜๋ฉด ์ฒ˜๋ฆฌ
forkJoin({
  profile: ajax.getJSON<UserProfile>('/api/user/1/profile'),
  posts: ajax.getJSON<UserPosts>('/api/user/1/posts'),
  followers: ajax.getJSON<UserFollowers>('/api/user/1/followers')
}).subscribe(({ profile, posts, followers }) => {
  // ์„ธ ์š”์ฒญ์ด ๋ชจ๋‘ ์™„๋ฃŒ๋œ ํ›„ ์‹คํ–‰
  console.log('ํ”„๋กœํ•„:', profile);
  console.log('๊ฒŒ์‹œ๊ธ€:', posts);
  console.log('ํŒ”๋กœ์›Œ:', followers);
});
๐Ÿ›ก๏ธ catchError: ์—๋Ÿฌ ์ฒ˜๋ฆฌ
์—๋Ÿฌ ์ฒ˜๋ฆฌ ํŒจํ„ด
import { of, throwError } from 'rxjs';
import { catchError, retry, map } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

interface ErrorResponse {
  code: number;
  message: string;
}

ajax.getJSON<User[]>('/api/users').pipe(
  map(users => users.filter(u => u.age >= 18)),
  retry(2), // ์‹คํŒจ ์‹œ 2๋ฒˆ ์žฌ์‹œ๋„
  catchError((error: ErrorResponse) => {
    if (error.code === 404) {
      return of([]); // ๋นˆ ๋ฐฐ์—ด๋กœ ๋Œ€์ฒด
    }
    if (error.code === 401) {
      window.location.href = '/login'; // ๋กœ๊ทธ์ธ ํŽ˜์ด์ง€๋กœ
      return of([]);
    }
    return throwError(() => new Error(`์•Œ ์ˆ˜ ์—†๋Š” ์—๋Ÿฌ: ${error.message}`));
  })
).subscribe({
  next: users => console.log('์œ ์ € ๋ชฉ๋ก:', users),
  error: err => console.error('์ฒ˜๋ฆฌ ๋ถˆ๊ฐ€ ์—๋Ÿฌ:', err)
});

๐Ÿ—๏ธ ์‹ค์ „ ํŒจํ„ด: ์ด๋ ‡๊ฒŒ ์“ฐ๋ฉด ๋ฉ๋‹ˆ๋‹ค

์ด๋ก ์€ ์ถฉ๋ถ„ํžˆ ๋ดค์œผ๋‹ˆ, ์ด์ œ ์‹ค์ œ ํ”„๋กœ์ ํŠธ์—์„œ ์–ด๋–ป๊ฒŒ ํ™œ์šฉํ•˜๋Š”์ง€ ์‚ดํŽด๋ด์š”! ์žฌ๋Šฅ๋„ท ๊ฐ™์€ ํ”Œ๋žซํผ์„ ๋งŒ๋“ ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ  ์‹ค์ „ ์˜ˆ์ œ๋ฅผ ์ž‘์„ฑํ•ด๋ณผ๊ฒŒ์š”. ๐ŸŽฏ

ํŒจํ„ด 1: ์ƒํƒœ ๊ด€๋ฆฌ ์„œ๋น„์Šค (BehaviorSubject ํ™œ์šฉ)
TypeScript ์ƒํƒœ ๊ด€๋ฆฌ ์„œ๋น„์Šค
import { BehaviorSubject, Observable } from 'rxjs';
import { map, distinctUntilChanged } from 'rxjs/operators';

// ์•ฑ ์ƒํƒœ ์ธํ„ฐํŽ˜์ด์Šค
interface AppState {
  user: User | null;
  isLoading: boolean;
  notifications: Notification[];
  theme: 'light' | 'dark';
}

// ์ดˆ๊ธฐ ์ƒํƒœ
const initialState: AppState = {
  user: null,
  isLoading: false,
  notifications: [],
  theme: 'light'
};

class StateService {
  private state$ = new BehaviorSubject<AppState>(initialState);

  // ์ „์ฒด ์ƒํƒœ ์ŠคํŠธ๋ฆผ
  getState(): Observable<AppState> {
    return this.state$.asObservable();
  }

  // ํŠน์ • ์Šฌ๋ผ์ด์Šค๋งŒ ์„ ํƒ (๋ถˆํ•„์š”ํ•œ ๋ฆฌ๋ Œ๋”๋ง ๋ฐฉ์ง€)
  select<K extends keyof AppState>(key: K): Observable<AppState[K]> {
    return this.state$.pipe(
      map(state => state[key]),
      distinctUntilChanged() // ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งŒ ๋ฐฉ์ถœ
    );
  }

  // ์ƒํƒœ ์—…๋ฐ์ดํŠธ
  setState(partial: Partial<AppState>): void {
    const currentState = this.state$.getValue();
    this.state$.next({ ...currentState, ...partial });
  }

  // ํŽธ์˜ ๋ฉ”์„œ๋“œ๋“ค
  setUser(user: User | null): void {
    this.setState({ user });
  }

  setLoading(isLoading: boolean): void {
    this.setState({ isLoading });
  }

  addNotification(notification: Notification): void {
    const notifications = [...this.state$.getValue().notifications, notification];
    this.setState({ notifications });
  }
}

// ์‚ฌ์šฉ ์˜ˆ์‹œ
const stateService = new StateService();

// ์œ ์ € ์ƒํƒœ๋งŒ ๊ตฌ๋…
stateService.select('user').subscribe(user => {
  if (user) {
    console.log(`ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค, ${user.name}๋‹˜!`);
  }
});

// ๋กœ๋”ฉ ์ƒํƒœ๋งŒ ๊ตฌ๋…
stateService.select('isLoading').subscribe(isLoading => {
  document.getElementById('spinner')!.style.display = isLoading ? 'block' : 'none';
});
ํŒจํ„ด 2: ๋ฌดํ•œ ์Šคํฌ๋กค ๊ตฌํ˜„
๋ฌดํ•œ ์Šคํฌ๋กค (Intersection Observer + RxJS)
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { switchMap, scan, tap, startWith } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

interface PagedResponse<T> {
  data: T[];
  page: number;
  hasMore: boolean;
}

interface TalentItem {
  id: number;
  title: string;
  price: number;
  seller: string;
}

class InfiniteScrollService {
  private page$ = new BehaviorSubject<number>(1);
  private isLoading$ = new BehaviorSubject<boolean>(false);
  private destroy$ = new Subject<void>();

  // ๋ˆ„์ ๋œ ์•„์ดํ…œ ์ŠคํŠธ๋ฆผ
  items$: Observable<TalentItem[]>;

  constructor() {
    this.items$ = this.page$.pipe(
      tap(() => this.isLoading$.next(true)),
      switchMap(page =>
        ajax.getJSON<PagedResponse<TalentItem>>(`/api/talents?page=${page}&limit=20`)
      ),
      tap(() => this.isLoading$.next(false)),
      scan((acc: TalentItem[], response) => {
        // ํŽ˜์ด์ง€ 1์ด๋ฉด ์ดˆ๊ธฐํ™”, ์•„๋‹ˆ๋ฉด ๋ˆ„์ 
        return response.page === 1
          ? response.data
          : [...acc, ...response.data];
      }, []),
      startWith([])
    );
  }

  loadNextPage(): void {
    const currentPage = this.page$.getValue();
    this.page$.next(currentPage + 1);
  }

  refresh(): void {
    this.page$.next(1);
  }

  destroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

// Intersection Observer๋กœ ์Šคํฌ๋กค ๊ฐ์ง€
function createScrollObserver(element: Element): Observable<boolean> {
  return new Observable(subscriber => {
    const observer = new IntersectionObserver(entries => {
      subscriber.next(entries[0].isIntersecting);
    });
    observer.observe(element);
    return () => observer.disconnect();
  });
}

// ์‚ฌ์šฉ
const scrollService = new InfiniteScrollService();
const sentinel = document.getElementById('scroll-sentinel')!;

createScrollObserver(sentinel).pipe(
  filter(isVisible => isVisible)
).subscribe(() => scrollService.loadNextPage());

scrollService.items$.subscribe(items => {
  renderItems(items);
});
ํŒจํ„ด 3: ์‹ค์‹œ๊ฐ„ ์•Œ๋ฆผ (WebSocket + RxJS)
WebSocket ์‹ค์‹œ๊ฐ„ ์•Œ๋ฆผ
import { Observable, Subject, timer } from 'rxjs';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { retryWhen, delay, tap, filter, map } from 'rxjs/operators';

interface NotificationMessage {
  type: 'message' | 'order' | 'review' | 'system';
  id: string;
  content: string;
  timestamp: number;
  userId: string;
}

class NotificationService {
  private socket$: WebSocketSubject<NotificationMessage>;
  private destroy$ = new Subject<void>();

  constructor(private userId: string) {
    this.socket$ = webSocket<NotificationMessage>({
      url: `wss://api.example.com/notifications?userId=${userId}`,
      openObserver: {
        next: () => console.log('WebSocket ์—ฐ๊ฒฐ๋จ!')
      },
      closeObserver: {
        next: () => console.log('WebSocket ์—ฐ๊ฒฐ ์ข…๋ฃŒ')
      }
    });
  }

  // ํŠน์ • ํƒ€์ž…์˜ ์•Œ๋ฆผ๋งŒ ๋ฐ›๊ธฐ
  getNotifications(type?: NotificationMessage['type']): Observable<NotificationMessage> {
    return this.socket$.pipe(
      filter(msg => !type || msg.type === type),
      retryWhen(errors =>
        errors.pipe(
          tap(err => console.log('์—ฐ๊ฒฐ ์˜ค๋ฅ˜, ์žฌ์—ฐ๊ฒฐ ์‹œ๋„...', err)),
          delay(3000) // 3์ดˆ ํ›„ ์žฌ์—ฐ๊ฒฐ
        )
      )
    );
  }

  // ๋ฉ”์‹œ์ง€ ์•Œ๋ฆผ๋งŒ
  getMessageNotifications(): Observable<NotificationMessage> {
    return this.getNotifications('message');
  }

  // ์ฃผ๋ฌธ ์•Œ๋ฆผ๋งŒ
  getOrderNotifications(): Observable<NotificationMessage> {
    return this.getNotifications('order');
  }

  disconnect(): void {
    this.socket$.complete();
    this.destroy$.next();
  }
}

// ์‚ฌ์šฉ
const notificationService = new NotificationService('user123');

// ๋ฉ”์‹œ์ง€ ์•Œ๋ฆผ ๊ตฌ๋…
notificationService.getMessageNotifications().subscribe(msg => {
  showToast(`์ƒˆ ๋ฉ”์‹œ์ง€: ${msg.content}`);
  updateBadgeCount();
});

// ์ฃผ๋ฌธ ์•Œ๋ฆผ ๊ตฌ๋…
notificationService.getOrderNotifications().subscribe(msg => {
  showOrderAlert(msg);
});
๐Ÿ’š ์‹ค๋ฌด ํŒ: ์žฌ๋Šฅ๋„ท์ฒ˜๋Ÿผ ์žฌ๋Šฅ ๊ฑฐ๋ž˜ ํ”Œ๋žซํผ์—์„œ๋Š” ์‹ค์‹œ๊ฐ„ ์ฑ„ํŒ…, ์ฃผ๋ฌธ ์ƒํƒœ ์—…๋ฐ์ดํŠธ, ๋ฆฌ๋ทฐ ์•Œ๋ฆผ ๋“ฑ ๋‹ค์–‘ํ•œ ์‹ค์‹œ๊ฐ„ ๊ธฐ๋Šฅ์ด ํ•„์š”ํ•ด์š”. RxJS์˜ WebSocket ์ง€์›๊ณผ Subject๋ฅผ ํ™œ์šฉํ•˜๋ฉด ์ด๋Ÿฐ ๊ธฐ๋Šฅ๋“ค์„ ๊น”๋”ํ•˜๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์–ด์š”!
ํŒจํ„ด 4: ํผ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ (์‹ค์‹œ๊ฐ„)
์‹ค์‹œ๊ฐ„ ํผ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ
import { fromEvent, combineLatest, Observable } from 'rxjs';
import { map, debounceTime, distinctUntilChanged, switchMap, startWith } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

interface ValidationResult {
  valid: boolean;
  message: string;
}

// ์ด๋ฉ”์ผ ํ˜•์‹ ๊ฒ€์‚ฌ
function validateEmailFormat(email: string): ValidationResult {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return {
    valid: emailRegex.test(email),
    message: emailRegex.test(email) ? '' : '์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ ํ˜•์‹์ด ์•„๋‹™๋‹ˆ๋‹ค'
  };
}

// ์ด๋ฉ”์ผ ์ค‘๋ณต ๊ฒ€์‚ฌ (์„œ๋ฒ„)
function checkEmailDuplicate(email: string): Observable<ValidationResult> {
  return ajax.getJSON<{ available: boolean }>(`/api/check-email?email=${email}`).pipe(
    map(response => ({
      valid: response.available,
      message: response.available ? '' : '์ด๋ฏธ ์‚ฌ์šฉ ์ค‘์ธ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค'
    }))
  );
}

// ํผ ์š”์†Œ
const emailInput = document.getElementById('email') as HTMLInputElement;
const passwordInput = document.getElementById('password') as HTMLInputElement;
const submitBtn = document.getElementById('submit') as HTMLButtonElement;

// ์ด๋ฉ”์ผ ์ŠคํŠธ๋ฆผ
const email$ = fromEvent<InputEvent>(emailInput, 'input').pipe(
  map(e => (e.target as HTMLInputElement).value),
  debounceTime(500),
  distinctUntilChanged(),
  startWith('')
);

// ์ด๋ฉ”์ผ ์œ ํšจ์„ฑ ์ŠคํŠธ๋ฆผ
const emailValidation$ = email$.pipe(
  switchMap(email => {
    const formatResult = validateEmailFormat(email);
    if (!formatResult.valid) return [formatResult]; // ํ˜•์‹ ์˜ค๋ฅ˜๋ฉด ์„œ๋ฒ„ ์š”์ฒญ ์•ˆ ํ•จ
    return checkEmailDuplicate(email);
  }),
  startWith({ valid: false, message: '' })
);

// ๋น„๋ฐ€๋ฒˆํ˜ธ ์ŠคํŠธ๋ฆผ
const password$ = fromEvent<InputEvent>(passwordInput, 'input').pipe(
  map(e => (e.target as HTMLInputElement).value),
  map(pw => ({
    valid: pw.length >= 8,
    message: pw.length >= 8 ? '' : '๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” 8์ž ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค'
  })),
  startWith({ valid: false, message: '' })
);

// ์ „์ฒด ํผ ์œ ํšจ์„ฑ
combineLatest([emailValidation$, password$]).pipe(
  map(([emailVal, pwVal]) => emailVal.valid && pwVal.valid)
).subscribe(isValid => {
  submitBtn.disabled = !isValid;
  submitBtn.style.opacity = isValid ? '1' : '0.5';
});

๐Ÿš€ ๊ณ ๊ธ‰ ํŒจํ„ด: ํ”„๋กœ์ฒ˜๋Ÿผ ์“ฐ๊ธฐ
์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ ๋งŒ๋“ค๊ธฐ

RxJS์˜ ์ง„์งœ ํŒŒ์›Œ๋Š” ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฑฐ์˜ˆ์š”! ๋ฐ˜๋ณต๋˜๋Š” ๋กœ์ง์„ ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์˜คํผ๋ ˆ์ดํ„ฐ๋กœ ์ถ”์ถœํ•  ์ˆ˜ ์žˆ์–ด์š”.

์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ
import { Observable, OperatorFunction } from 'rxjs';
import { map, filter, catchError, tap } from 'rxjs/operators';
import { of } from 'rxjs';

// ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ: ๋กœ๋”ฉ ์ƒํƒœ ๊ด€๋ฆฌ
function withLoading<T>(
  setLoading: (loading: boolean) => void
): OperatorFunction<T, T> {
  return (source: Observable<T>) =>
    new Observable(subscriber => {
      setLoading(true);
      return source.subscribe({
        next: value => {
          setLoading(false);
          subscriber.next(value);
        },
        error: err => {
          setLoading(false);
          subscriber.error(err);
        },
        complete: () => {
          setLoading(false);
          subscriber.complete();
        }
      });
    });
}

// ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ: ์—๋Ÿฌ ๋กœ๊น…
function logError<T>(context: string): OperatorFunction<T, T> {
  return catchError(error => {
    console.error(`[${context}] ์—๋Ÿฌ ๋ฐœ์ƒ:`, error);
    // ์—๋Ÿฌ ๋ชจ๋‹ˆํ„ฐ๋ง ์„œ๋น„์Šค์— ์ „์†ก
    sendToErrorMonitoring({ context, error, timestamp: Date.now() });
    return of(null as unknown as T);
  });
}

// ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ: null/undefined ํ•„ํ„ฐ๋ง
function filterNullish<T>(): OperatorFunction<T | null | undefined, T> {
  return filter((value): value is T => value !== null && value !== undefined);
}

// ์‚ฌ์šฉ ์˜ˆ์‹œ
const isLoading = { value: false };

ajax.getJSON<Product[]>('/api/products').pipe(
  withLoading(loading => isLoading.value = loading),
  filterNullish(),
  logError('ProductService')
).subscribe(products => {
  console.log('์ƒํ’ˆ ๋ชฉ๋ก:', products);
});
๋ฉ”๋ชจ์ด์ œ์ด์…˜ ํŒจํ„ด (shareReplay)
shareReplay๋กœ ์บ์‹ฑ
import { Observable } from 'rxjs';
import { shareReplay, tap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

class CategoryService {
  // ์นดํ…Œ๊ณ ๋ฆฌ ๋ชฉ๋ก์„ ์บ์‹ฑ (์—ฌ๋Ÿฌ ์ปดํฌ๋„ŒํŠธ์—์„œ ๊ณต์œ )
  private categories$: Observable<Category[]> | null = null;

  getCategories(): Observable<Category[]> {
    if (!this.categories$) {
      this.categories$ = ajax.getJSON<Category[]>('/api/categories').pipe(
        tap(() => console.log('API ํ˜ธ์ถœ๋จ (์ตœ์ดˆ 1ํšŒ๋งŒ)')),
        shareReplay(1) // ๋งˆ์ง€๋ง‰ ๊ฐ’์„ ์บ์‹ฑ, ์ƒˆ ๊ตฌ๋…์ž์—๊ฒŒ ์ฆ‰์‹œ ์ „๋‹ฌ
      );
    }
    return this.categories$;
  }

  clearCache(): void {
    this.categories$ = null;
  }
}

const categoryService = new CategoryService();

// ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ๊ตฌ๋…ํ•ด๋„ API๋Š” 1๋ฒˆ๋งŒ ํ˜ธ์ถœ๋จ!
categoryService.getCategories().subscribe(cats => console.log('์ปดํฌ๋„ŒํŠธA:', cats));
categoryService.getCategories().subscribe(cats => console.log('์ปดํฌ๋„ŒํŠธB:', cats));
categoryService.getCategories().subscribe(cats => console.log('์ปดํฌ๋„ŒํŠธC:', cats));
// API ํ˜ธ์ถœ๋จ (์ตœ์ดˆ 1ํšŒ๋งŒ) โ†’ ์ถœ๋ ฅ 1๋ฒˆ
// ์ปดํฌ๋„ŒํŠธA, B, C ๋ชจ๋‘ ๊ฐ™์€ ๋ฐ์ดํ„ฐ ๋ฐ›์Œ
๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ๋ฐฉ์ง€: takeUntil ํŒจํ„ด
Angular ์ปดํฌ๋„ŒํŠธ์—์„œ ๊ตฌ๋… ๊ด€๋ฆฌ
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil, interval } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  template: `...`
})
export class DashboardComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit(): void {
    // 1์ดˆ๋งˆ๋‹ค ๋ฐ์ดํ„ฐ ๊ฐฑ์‹ 
    interval(1000).pipe(
      takeUntil(this.destroy$) // ์ปดํฌ๋„ŒํŠธ ์†Œ๋ฉธ ์‹œ ์ž๋™ ๊ตฌ๋… ํ•ด์ œ!
    ).subscribe(() => this.refreshData());

    // ๋‹ค๋ฅธ ๊ตฌ๋…๋“ค๋„ ๋™์ผํ•˜๊ฒŒ
    this.userService.getCurrentUser().pipe(
      takeUntil(this.destroy$)
    ).subscribe(user => this.currentUser = user);
  }

  ngOnDestroy(): void {
    this.destroy$.next();   // ๋ชจ๋“  takeUntil ํŠธ๋ฆฌ๊ฑฐ
    this.destroy$.complete(); // Subject ์ •๋ฆฌ
    // ํ•œ ๋ฒˆ์— ๋ชจ๋“  ๊ตฌ๋… ํ•ด์ œ! ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ์—†์Œ โœ…
  }

  private refreshData(): void {
    // ๋ฐ์ดํ„ฐ ๊ฐฑ์‹  ๋กœ์ง
  }
}
โš ๏ธ ์ฃผ์˜: ๊ตฌ๋…์„ ํ•ด์ œํ•˜์ง€ ์•Š์œผ๋ฉด ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์†Œ๋ฉธ๋œ ํ›„์—๋„ ๊ตฌ๋…์ด ์‚ด์•„์žˆ์–ด์„œ ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜๊ฐ€ ๋ฐœ์ƒํ•ด์š”! takeUntil, take(1), unsubscribe() ์ค‘ ์ƒํ™ฉ์— ๋งž๋Š” ๋ฐฉ๋ฒ•์„ ๋ฐ˜๋“œ์‹œ ์‚ฌ์šฉํ•˜์„ธ์š”.
๊ณ ๊ธ‰ ์—๋Ÿฌ ์ฒ˜๋ฆฌ: ์ง€์ˆ˜ ๋ฐฑ์˜คํ”„ ์žฌ์‹œ๋„
์ง€์ˆ˜ ๋ฐฑ์˜คํ”„ (Exponential Backoff)
import { Observable, throwError, timer } from 'rxjs';
import { mergeMap, retryWhen, tap } from 'rxjs/operators';

function exponentialBackoff<T>(
  maxRetries: number = 3,
  initialDelay: number = 1000
): (source: Observable<T>) => Observable<T> {
  return (source: Observable<T>) =>
    source.pipe(
      retryWhen(errors =>
        errors.pipe(
          mergeMap((error, index) => {
            const retryAttempt = index + 1;

            if (retryAttempt > maxRetries) {
              return throwError(() => error);
            }

            const delay = initialDelay * Math.pow(2, index); // 1s, 2s, 4s...
            console.log(`์žฌ์‹œ๋„ ${retryAttempt}/${maxRetries}, ${delay}ms ํ›„ ์žฌ์‹œ๋„`);

            return timer(delay);
          }),
          tap(retryAttempt => {
            console.log(`์žฌ์‹œ๋„ ์ค‘...`);
          })
        )
      )
    );
}

// ์‚ฌ์šฉ
ajax.getJSON<User[]>('/api/users').pipe(
  exponentialBackoff(3, 1000)
).subscribe({
  next: users => console.log('์„ฑ๊ณต:', users),
  error: err => console.error('์ตœ์ข… ์‹คํŒจ:', err)
});
// ์‹คํŒจ ์‹œ: 1์ดˆ ํ›„ ์žฌ์‹œ๋„ โ†’ 2์ดˆ ํ›„ ์žฌ์‹œ๋„ โ†’ 4์ดˆ ํ›„ ์žฌ์‹œ๋„ โ†’ ์ตœ์ข… ์—๋Ÿฌ

๐Ÿงช RxJS ์ฝ”๋“œ ํ…Œ์ŠคํŒ…

RxJS ์ฝ”๋“œ๋ฅผ ํ…Œ์ŠคํŠธํ•˜๋Š” ๊ฑด ์ฒ˜์Œ์—” ์ข€ ๋‚ฏ์„ค ์ˆ˜ ์žˆ์–ด์š”. ๋น„๋™๊ธฐ ์ŠคํŠธ๋ฆผ์„ ์–ด๋–ป๊ฒŒ ํ…Œ์ŠคํŠธํ•˜๋ƒ๊ณ ์š”? RxJS๋Š” ๋งˆ๋ธ” ํ…Œ์ŠคํŒ…(Marble Testing)์ด๋ผ๋Š” ๋…ํŠนํ•œ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ด์š”!

๋งˆ๋ธ” ๋‹ค์ด์–ด๊ทธ๋žจ์ด๋ž€?

๋งˆ๋ธ” ๋‹ค์ด์–ด๊ทธ๋žจ์€ ์‹œ๊ฐ„ ์ถ• ์œ„์— ์ด๋ฒคํŠธ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด์—์š”. ๋ฌธ์ž๋กœ ํ‘œํ˜„ํ•˜๋ฉด ์ด๋ ‡๊ฒŒ ์ƒ๊ฒผ์–ด์š”:

--a--b--c--|

- : 10ms ๊ฒฝ๊ณผ
a, b, c : ๊ฐ’ ๋ฐฉ์ถœ
| : ์™„๋ฃŒ
# : ์—๋Ÿฌ
^ : ๊ตฌ๋… ์‹œ์ž‘์ 
๋งˆ๋ธ” ํ…Œ์ŠคํŒ… ์˜ˆ์‹œ (Jest + rxjs/testing)
import { TestScheduler } from 'rxjs/testing';
import { map, filter, debounceTime } from 'rxjs/operators';

describe('RxJS ์˜คํผ๋ ˆ์ดํ„ฐ ํ…Œ์ŠคํŠธ', () => {
  let testScheduler: TestScheduler;

  beforeEach(() => {
    testScheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  test('map ์˜คํผ๋ ˆ์ดํ„ฐ: ์ˆซ์ž๋ฅผ 2๋ฐฐ๋กœ', () => {
    testScheduler.run(({ cold, expectObservable }) => {
      const source$ = cold('--a--b--c--|', { a: 1, b: 2, c: 3 });
      const result$ = source$.pipe(map(x => x * 2));

      expectObservable(result$).toBe('--a--b--c--|', { a: 2, b: 4, c: 6 });
    });
  });

  test('filter ์˜คํผ๋ ˆ์ดํ„ฐ: ์ง์ˆ˜๋งŒ ํ†ต๊ณผ', () => {
    testScheduler.run(({ cold, expectObservable }) => {
      const source$ = cold('--a--b--c--d--|', { a: 1, b: 2, c: 3, d: 4 });
      const result$ = source$.pipe(filter(x => x % 2 === 0));

      expectObservable(result$).toBe('-----b--------d--|', { b: 2, d: 4 });
    });
  });

  test('debounceTime: 300ms ๋””๋ฐ”์šด์Šค', () => {
    testScheduler.run(({ cold, expectObservable }) => {
      // ๋น ๋ฅด๊ฒŒ ์—ฐ์† ์ž…๋ ฅ
      const source$ = cold('a-b-c-----------d|');
      const result$ = source$.pipe(debounceTime(300, testScheduler));

      // ๋งˆ์ง€๋ง‰ c๋งŒ 300ms ํ›„ ๋ฐฉ์ถœ, d๋Š” ์™„๋ฃŒ ์ „ ๋ฐฉ์ถœ
      expectObservable(result$).toBe('---------------c-d|');
    });
  });
});
์„œ๋น„์Šค ๋‹จ์œ„ ํ…Œ์ŠคํŠธ
์„œ๋น„์Šค ํ…Œ์ŠคํŠธ
import { of, throwError } from 'rxjs';
import { UserService } from './user.service';

// HTTP ํด๋ผ์ด์–ธํŠธ ๋ชจํ‚น
const mockHttp = {
  get: jest.fn()
};

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    service = new UserService(mockHttp as any);
    jest.clearAllMocks();
  });

  test('getUser: ์„ฑ๊ณต ์ผ€์ด์Šค', done => {
    const mockUser: User = { id: 1, name: '๊น€์ฒ ์ˆ˜', age: 25, email: 'kim@test.com' };
    mockHttp.get.mockReturnValue(of(mockUser));

    service.getUser(1).subscribe({
      next: user => {
        expect(user).toEqual(mockUser);
        expect(mockHttp.get).toHaveBeenCalledWith('/api/users/1');
        done();
      }
    });
  });

  test('getUser: ์—๋Ÿฌ ์ผ€์ด์Šค', done => {
    mockHttp.get.mockReturnValue(throwError(() => new Error('404 Not Found')));

    service.getUser(999).subscribe({
      error: err => {
        expect(err.message).toContain('404');
        done();
      }
    });
  });
});

โšก ์„ฑ๋Šฅ ์ตœ์ ํ™” ํŒ
1. ๋ถˆํ•„์š”ํ•œ ๊ตฌ๋… ์ตœ์†Œํ™”
share() vs shareReplay()
import { share, shareReplay } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

// โŒ ๋‚˜์œ ์˜ˆ: ๊ตฌ๋…ํ•  ๋•Œ๋งˆ๋‹ค API ํ˜ธ์ถœ
const users$ = ajax.getJSON<User[]>('/api/users');
users$.subscribe(u => console.log('A:', u)); // API ํ˜ธ์ถœ
users$.subscribe(u => console.log('B:', u)); // ๋˜ API ํ˜ธ์ถœ!

// โœ… ์ข‹์€ ์˜ˆ: share() - ํ˜„์žฌ ๊ตฌ๋…์ž๋“ค๊ณผ ๊ณต์œ 
const sharedUsers$ = ajax.getJSON<User[]>('/api/users').pipe(share());
sharedUsers$.subscribe(u => console.log('A:', u)); // API ํ˜ธ์ถœ
sharedUsers$.subscribe(u => console.log('B:', u)); // ๊ณต์œ ๋จ (๋™์‹œ ๊ตฌ๋… ์‹œ)

// โœ… ๋” ์ข‹์€ ์˜ˆ: shareReplay(1) - ๋‚˜์ค‘์— ๊ตฌ๋…ํ•ด๋„ ์บ์‹œ๋œ ๊ฐ’ ๋ฐ›์Œ
const cachedUsers$ = ajax.getJSON<User[]>('/api/users').pipe(shareReplay(1));
cachedUsers$.subscribe(u => console.log('A:', u)); // API ํ˜ธ์ถœ
setTimeout(() => {
  cachedUsers$.subscribe(u => console.log('B:', u)); // ์บ์‹œ๋œ ๊ฐ’ ์ฆ‰์‹œ ๋ฐ›์Œ!
}, 5000);
2. ์˜ฌ๋ฐ”๋ฅธ ๊ณ ์ฐจ ์˜คํผ๋ ˆ์ดํ„ฐ ์„ ํƒ
๐ŸŽฏ ์–ธ์ œ ์–ด๋–ค ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ?
โ€ข ๊ฒ€์ƒ‰/์ž๋™์™„์„ฑ โ†’ switchMap (์ตœ์‹  ์š”์ฒญ๋งŒ ์œ ํšจ)
โ€ข ํŒŒ์ผ ์—…๋กœ๋“œ ํ โ†’ concatMap (์ˆœ์„œ ๋ณด์žฅ)
โ€ข ๋…๋ฆฝ์  ๋ณ‘๋ ฌ ์š”์ฒญ โ†’ mergeMap (๋™์‹œ ์‹คํ–‰)
โ€ข ์ค‘๋ณต ํด๋ฆญ ๋ฐฉ์ง€ โ†’ exhaustMap (์ง„ํ–‰ ์ค‘์ด๋ฉด ๋ฌด์‹œ)
3. ๊ตฌ๋… ์ˆ˜ ์ œํ•œ (mergeMap์˜ concurrency)
๋™์‹œ ์š”์ฒญ ์ˆ˜ ์ œํ•œ
import { from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

const fileIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// ๋™์‹œ์— ์ตœ๋Œ€ 3๊ฐœ๋งŒ ์š”์ฒญ (์„œ๋ฒ„ ๋ถ€ํ•˜ ๋ฐฉ์ง€)
from(fileIds).pipe(
  mergeMap(
    id => ajax.getJSON(`/api/files/${id}`),
    3 // concurrency: ๋™์‹œ ์‹คํ–‰ ์ˆ˜ ์ œํ•œ
  )
).subscribe(file => {
  console.log('ํŒŒ์ผ ๋กœ๋“œ๋จ:', file);
});
4. ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ strict ๋ชจ๋“œ ํ™œ์šฉ
tsconfig.json ์„ค์ •
{
  "compilerOptions": {
    "strict": true,           // ์—„๊ฒฉ ๋ชจ๋“œ ํ™œ์„ฑํ™”
    "strictNullChecks": true, // null/undefined ์ฒดํฌ
    "noImplicitAny": true,    // any ํƒ€์ž… ์•”๋ฌต์  ์‚ฌ์šฉ ๊ธˆ์ง€
    "strictFunctionTypes": true,
    "target": "ES2020",
    "lib": ["ES2020", "DOM"],
    "moduleResolution": "node"
  }
}
๐Ÿ’š strict ๋ชจ๋“œ๋ฅผ ์ผœ๋ฉด RxJS ์˜คํผ๋ ˆ์ดํ„ฐ๋“ค์˜ ํƒ€์ž… ์ถ”๋ก ์ด ํ›จ์”ฌ ์ •ํ™•ํ•ด์ ธ์š”. ์ฒ˜์Œ์—” ์—๋Ÿฌ๊ฐ€ ๋งŽ์ด ๋‚˜์„œ ๊ท€์ฐฎ์„ ์ˆ˜ ์žˆ์ง€๋งŒ, ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๋ฅผ ์ปดํŒŒ์ผ ํƒ€์ž„์— ์žก์•„์ฃผ๋‹ˆ๊นŒ ์žฅ๊ธฐ์ ์œผ๋กœ ํ›จ์”ฌ ์ด๋“์ด์—์š”!

๐Ÿ“ ์‹ค์ œ ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ ์˜ˆ์‹œ

RxJS + TypeScript ํ”„๋กœ์ ํŠธ๋ฅผ ์–ด๋–ป๊ฒŒ ๊ตฌ์กฐํ™”ํ•˜๋ฉด ์ข‹์„์ง€ ์‚ดํŽด๋ด์š”. ์žฌ๋Šฅ๋„ท์ฒ˜๋Ÿผ ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์ด ์žˆ๋Š” ํ”Œ๋žซํผ์„ ์˜ˆ์‹œ๋กœ ๋“ค์–ด๋ณผ๊ฒŒ์š”!

ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ
src/
โ”œโ”€โ”€ services/
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ”œโ”€โ”€ base-api.service.ts      # ๊ณตํ†ต HTTP ๋กœ์ง
โ”‚   โ”‚   โ”œโ”€โ”€ user-api.service.ts      # ์œ ์ € ๊ด€๋ จ API
โ”‚   โ”‚   โ””โ”€โ”€ talent-api.service.ts    # ์žฌ๋Šฅ ๊ด€๋ จ API
โ”‚   โ”œโ”€โ”€ state/
โ”‚   โ”‚   โ”œโ”€โ”€ app-state.service.ts     # ์ „์—ญ ์ƒํƒœ ๊ด€๋ฆฌ
โ”‚   โ”‚   โ””โ”€โ”€ user-state.service.ts    # ์œ ์ € ์ƒํƒœ
โ”‚   โ””โ”€โ”€ realtime/
โ”‚       โ””โ”€โ”€ notification.service.ts  # ์‹ค์‹œ๊ฐ„ ์•Œ๋ฆผ
โ”œโ”€โ”€ operators/
โ”‚   โ”œโ”€โ”€ with-loading.operator.ts     # ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ
โ”‚   โ”œโ”€โ”€ log-error.operator.ts
โ”‚   โ””โ”€โ”€ filter-nullish.operator.ts
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ user.model.ts               # ํƒ€์ž… ์ •์˜
โ”‚   โ”œโ”€โ”€ talent.model.ts
โ”‚   โ””โ”€โ”€ api-response.model.ts
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ rx-utils.ts                  # RxJS ์œ ํ‹ธ๋ฆฌํ‹ฐ
    โ””โ”€โ”€ type-guards.ts               # ํƒ€์ž… ๊ฐ€๋“œ
base-api.service.ts (๊ณตํ†ต HTTP ์„œ๋น„์Šค)
import { Observable, throwError } from 'rxjs';
import { catchError, map, retry, timeout } from 'rxjs/operators';
import { ajax, AjaxResponse } from 'rxjs/ajax';

interface ApiConfig {
  baseUrl: string;
  timeout: number;
  retries: number;
}

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

export class BaseApiService {
  private config: ApiConfig = {
    baseUrl: 'https://api.example.com',
    timeout: 10000,
    retries: 2
  };

  protected get<T>(endpoint: string): Observable<T> {
    const token = localStorage.getItem('token');
    return ajax<ApiResponse<T>>({
      url: `${this.config.baseUrl}${endpoint}`,
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {})
      }
    }).pipe(
      timeout(this.config.timeout),
      retry(this.config.retries),
      map((response: AjaxResponse<ApiResponse<T>>) => response.response.data),
      catchError(this.handleError)
    );
  }

  protected post<T, B>(endpoint: string, body: B): Observable<T> {
    const token = localStorage.getItem('token');
    return ajax<ApiResponse<T>>({
      url: `${this.config.baseUrl}${endpoint}`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {})
      },
      body: JSON.stringify(body)
    }).pipe(
      timeout(this.config.timeout),
      map(response => response.response.data),
      catchError(this.handleError)
    );
  }

  private handleError(error: any): Observable<never> {
    if (error.status === 401) {
      // ํ† ํฐ ๋งŒ๋ฃŒ ์ฒ˜๋ฆฌ
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return throwError(() => ({
      status: error.status,
      message: error.response?.message || '์•Œ ์ˆ˜ ์—†๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค'
    }));
  }
}

// ์žฌ๋Šฅ API ์„œ๋น„์Šค
export class TalentApiService extends BaseApiService {
  getTalents(params: TalentSearchParams): Observable<Talent[]> {
    const query = new URLSearchParams(params as any).toString();
    return this.get<Talent[]>(`/talents?${query}`);
  }

  getTalentById(id: number): Observable<Talent> {
    return this.get<Talent>(`/talents/${id}`);
  }

  createTalent(talent: CreateTalentDto): Observable<Talent> {
    return this.post<Talent, CreateTalentDto>('/talents', talent);
  }
}

๐Ÿšจ ์ž์ฃผ ํ•˜๋Š” ์‹ค์ˆ˜ TOP 5
1 ๊ตฌ๋… ํ•ด์ œ ์•ˆ ํ•˜๊ธฐ (๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜)

์ปดํฌ๋„ŒํŠธ๊ฐ€ ์†Œ๋ฉธ๋  ๋•Œ ๊ตฌ๋…์„ ํ•ด์ œํ•˜์ง€ ์•Š์œผ๋ฉด ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜๊ฐ€ ๋ฐœ์ƒํ•ด์š”. takeUntil(destroy$) ํŒจํ„ด์„ ๋ฐ˜๋“œ์‹œ ์‚ฌ์šฉํ•˜์„ธ์š”!

2 ์ค‘์ฒฉ ๊ตฌ๋… (subscribe ์•ˆ์— subscribe)

subscribe ์•ˆ์— ๋˜ subscribe๋ฅผ ๋„ฃ๋Š” ๊ฑด ์ฝœ๋ฐฑ ์ง€์˜ฅ๊ณผ ๊ฐ™์•„์š”. switchMap, mergeMap ๋“ฑ ๊ณ ์ฐจ ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”!

3 ์—๋Ÿฌ ์ฒ˜๋ฆฌ ๋ˆ„๋ฝ

์—๋Ÿฌ ํ•ธ๋“ค๋Ÿฌ ์—†์ด ๊ตฌ๋…ํ•˜๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ ์‹œ ์ŠคํŠธ๋ฆผ์ด ์ข…๋ฃŒ๋˜๊ณ  ์•ฑ์ด ๋ฉˆ์ถœ ์ˆ˜ ์žˆ์–ด์š”. ํ•ญ์ƒ catchError๋ฅผ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ subscribe์˜ error ์ฝœ๋ฐฑ์„ ์ง€์ •ํ•˜์„ธ์š”!

4 Cold Observable์„ Hot์ฒ˜๋Ÿผ ์‚ฌ์šฉ

๊ฐ™์€ HTTP ์š”์ฒญ Observable์„ ์—ฌ๋Ÿฌ ๋ฒˆ ๊ตฌ๋…ํ•˜๋ฉด ์š”์ฒญ์ด ์—ฌ๋Ÿฌ ๋ฒˆ ๋ฐœ์ƒํ•ด์š”. shareReplay(1)๋กœ ์บ์‹ฑํ•˜๊ฑฐ๋‚˜ Subject๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”!

5 any ํƒ€์ž… ๋‚จ์šฉ

TypeScript๋ฅผ ์“ฐ๋Š” ์ด์œ ๊ฐ€ ํƒ€์ž… ์•ˆ์ „์„ฑ์ธ๋ฐ, any๋ฅผ ๋‚จ์šฉํ•˜๋ฉด ์˜๋ฏธ๊ฐ€ ์—†์–ด์š”. ์ œ๋„ค๋ฆญ๊ณผ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ ๊ทน ํ™œ์šฉํ•˜์„ธ์š”!


๐Ÿ—บ๏ธ RxJS + TypeScript ํ•™์Šต ๋กœ๋“œ๋งต

์ฒ˜์Œ ์‹œ์ž‘ํ•˜๋Š” ๋ถ„๋“ค์„ ์œ„ํ•œ ๋‹จ๊ณ„๋ณ„ ํ•™์Šต ๊ฐ€์ด๋“œ์˜ˆ์š”! ๋‹จ๊ณ„๋ฅผ ๊ฑด๋„ˆ๋›ฐ์ง€ ๋ง๊ณ  ์ฐจ๊ทผ์ฐจ๊ทผ ๋”ฐ๋ผ๊ฐ€๋ฉด ์–ด๋А์ƒˆ RxJS ๊ณ ์ˆ˜๊ฐ€ ๋˜์–ด ์žˆ์„ ๊ฑฐ์˜ˆ์š” ๐Ÿ’ช

๐Ÿ“š ๋‹จ๊ณ„๋ณ„ ํ•™์Šต ๋กœ๋“œ๋งต 1๋‹จ๊ณ„: ๊ธฐ์ดˆ TypeScript ๊ธฐ๋ณธ Promise/async-await ์ด๋ฒคํŠธ ๋ฃจํ”„ ์ดํ•ด 2๋‹จ๊ณ„: RxJS ์ž…๋ฌธ Observable/Observer ๊ธฐ๋ณธ ์˜คํผ๋ ˆ์ดํ„ฐ Subject ์ข…๋ฅ˜ 3๋‹จ๊ณ„: ์ค‘๊ธ‰ ๊ณ ์ฐจ ์˜คํผ๋ ˆ์ดํ„ฐ ์—๋Ÿฌ ์ฒ˜๋ฆฌ ํŒจํ„ด TypeScript ์ œ๋„ค๋ฆญ 4๋‹จ๊ณ„: ๊ณ ๊ธ‰ ์ปค์Šคํ…€ ์˜คํผ๋ ˆ์ดํ„ฐ ๋งˆ๋ธ” ํ…Œ์ŠคํŒ… ์„ฑ๋Šฅ ์ตœ์ ํ™” ๐Ÿ› ๏ธ ๋‹จ๊ณ„๋ณ„ ์‹ค์Šต ํ”„๋กœ์ ํŠธ ํ”„๋กœ์ ํŠธ 1 ํƒ€์ด๋จธ ์•ฑ interval, take ๊ธฐ๋ณธ ๊ตฌ๋… ๊ด€๋ฆฌ ํ”„๋กœ์ ํŠธ 2 ๊ฒ€์ƒ‰ ์ž๋™์™„์„ฑ debounceTime switchMap + API ํ”„๋กœ์ ํŠธ 3 ์‡ผํ•‘์นดํŠธ ์ƒํƒœ๊ด€๋ฆฌ BehaviorSubject combineLatest ํ”„๋กœ์ ํŠธ 4 ์‹ค์‹œ๊ฐ„ ์ฑ„ํŒ…์•ฑ WebSocket retryWhen + ํ…Œ์ŠคํŒ… ๐Ÿ“– ์ถ”์ฒœ ํ•™์Šต ๋ฆฌ์†Œ์Šค ๊ณต์‹ ๋ฌธ์„œ rxjs.dev (๊ณต์‹ ์‚ฌ์ดํŠธ) rxmarbles.com (๋งˆ๋ธ” ์‹œ๊ฐํ™”) TypeScript ๊ณต์‹ ํ•ธ๋“œ๋ถ learnrxjs.io ์‹ค์Šต ๋„๊ตฌ StackBlitz (์˜จ๋ผ์ธ IDE) CodeSandbox RxViz (์ŠคํŠธ๋ฆผ ์‹œ๊ฐํ™”) TypeScript Playground ์ปค๋ฎค๋‹ˆํ‹ฐ GitHub RxJS Issues Stack Overflow Reddit r/typescript Discord TypeScript ์„œ๋ฒ„

๐ŸŽฏ ๋งˆ๋ฌด๋ฆฌ: RxJS + TypeScript, ์ด์ œ ๋‘๋ ต์ง€ ์•Š์ฃ ?

์ž, ์—ฌ๊ธฐ๊นŒ์ง€ RxJS์™€ TypeScript๋ฅผ ์ด์šฉํ•œ ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์— ๋Œ€ํ•ด ๊ฝค ๊นŠ๊ฒŒ ์‚ดํŽด๋ดค์–ด์š”! ์ฒ˜์Œ์—” Observable, Subject, ์˜คํผ๋ ˆ์ดํ„ฐ๋“ค์ด ๋‚ฏ์„ค๊ณ  ๋ณต์žกํ•ด ๋ณด์ด์ง€๋งŒ, ํ•ต์‹ฌ ๊ฐœ๋… ๋ช‡ ๊ฐ€์ง€๋งŒ ์ œ๋Œ€๋กœ ์ดํ•ดํ•˜๋ฉด ๋‚˜๋จธ์ง€๋Š” ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋”ฐ๋ผ์™€์š” ๐Ÿ˜Š

๐ŸŒŸ ํ•ต์‹ฌ ์š”์•ฝ:
Observable ๋ฐ์ดํ„ฐ ์ŠคํŠธ๋ฆผ์˜ ์‹œ์ž‘์ , ๊ตฌ๋… ์ „๊นŒ์ง€ ์‹คํ–‰ ์•ˆ ๋จ
Subject Observable + Observer, ๋ฉ€ํ‹ฐ์บ์ŠคํŒ… ๊ฐ€๋Šฅ
pipe() ์˜คํผ๋ ˆ์ดํ„ฐ ์ฒด์ด๋‹์œผ๋กœ ๋ฐ์ดํ„ฐ ๋ณ€ํ™˜
TypeScript ์ œ๋„ค๋ฆญ์œผ๋กœ ํƒ€์ž… ์•ˆ์ „ํ•œ ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ
๊ตฌ๋… ํ•ด์ œ takeUntil, unsubscribe๋กœ ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜ ๋ฐฉ์ง€

RxJS๋ฅผ ์ฒ˜์Œ ๋ฐฐ์šธ ๋•Œ ๊ฐ€์žฅ ์ข‹์€ ๋ฐฉ๋ฒ•์€ ์ž‘์€ ๊ฒƒ๋ถ€ํ„ฐ ์ง์ ‘ ๋งŒ๋“ค์–ด๋ณด๋Š” ๊ฒƒ์ด์—์š”. ํƒ€์ด๋จธ ์•ฑ, ๊ฒ€์ƒ‰ ์ž๋™์™„์„ฑ, ์‹ค์‹œ๊ฐ„ ์•Œ๋ฆผ ๊ฐ™์€ ์ž‘์€ ํ”„๋กœ์ ํŠธ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์ ์  ๋ณต์žกํ•œ ๊ธฐ๋Šฅ์œผ๋กœ ํ™•์žฅํ•ด๋‚˜๊ฐ€๋ฉด ๋ผ์š”.

๋งŒ์•ฝ RxJS๋‚˜ TypeScript ๊ด€๋ จ ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ ๋„์›€์ด ํ•„์š”ํ•˜๋‹ค๋ฉด, ์žฌ๋Šฅ๋„ท์—์„œ TypeScript/RxJS ์ „๋ฌธ๊ฐ€๋ฅผ ์ฐพ์•„๋ณด๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ด์—์š”! ๋‹ค์–‘ํ•œ ๊ฐœ๋ฐœ ์žฌ๋Šฅ์„ ๊ฐ€์ง„ ๋ถ„๋“ค์ด ์—ฌ๋Ÿฌ๋ถ„์˜ ํ”„๋กœ์ ํŠธ๋ฅผ ๋„์™€์ค„ ์ˆ˜ ์žˆ๊ฑฐ๋“ ์š” ๐Ÿค

๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ์€ ์ฒ˜์Œ์—” ํŒจ๋Ÿฌ๋‹ค์ž„ ์ „ํ™˜์ด ํ•„์š”ํ•ด์„œ ์–ด๋ ต๊ฒŒ ๋А๊ปด์ง€์ง€๋งŒ, ํ•œ ๋ฒˆ ์ต์ˆ™ํ•ด์ง€๋ฉด ๋ณต์žกํ•œ ๋น„๋™๊ธฐ ๋กœ์ง์„ ํ›จ์”ฌ ์šฐ์•„ํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด์š”. ํŠนํžˆ TypeScript์™€ ํ•จ๊ป˜ ์“ฐ๋ฉด ํƒ€์ž… ์•ˆ์ „์„ฑ๊นŒ์ง€ ๋ณด์žฅ๋˜๋‹ˆ๊นŒ, ๋Œ€๊ทœ๋ชจ ํ”„๋กœ์ ํŠธ์—์„œ ์ง„๊ฐ€๋ฅผ ๋ฐœํœ˜ํ•ด์š”! ๐Ÿ’ช

๐Ÿ’š ๋งˆ์ง€๋ง‰ ํŒ: RxJS๋ฅผ ๋ฐฐ์šธ ๋•Œ rxmarbles.com์„ ๊ผญ ํ™œ์šฉํ•ด๋ณด์„ธ์š”! ๊ฐ ์˜คํผ๋ ˆ์ดํ„ฐ๊ฐ€ ์–ด๋–ป๊ฒŒ ๋™์ž‘ํ•˜๋Š”์ง€ ์ธํ„ฐ๋ž™ํ‹ฐ๋ธŒํ•˜๊ฒŒ ์‹œ๊ฐํ™”ํ•ด์„œ ๋ณด์—ฌ์ค˜์„œ ์ดํ•ดํ•˜๋Š” ๋ฐ ์ •๋ง ๋„์›€์ด ๋ผ์š”. ๋งˆ๋ธ” ๋‹ค์ด์–ด๊ทธ๋žจ์„ ์ง์ ‘ ์กฐ์ž‘ํ•ด๋ณด๋ฉด์„œ ๋ฐฐ์šฐ๋ฉด ํ›จ์”ฌ ๋น ๋ฅด๊ฒŒ ์ตํž ์ˆ˜ ์žˆ์–ด์š”!
๋Œ“๊ธ€ ์ž‘์„ฑ

์ด ๊ธ€์— ๋Œ€ํ•œ ์—ฌ๋Ÿฌ๋ถ„์˜ ์ƒ๊ฐ์„ ๋“ค๋ ค์ฃผ์„ธ์š”

๋Œ“๊ธ€ 0
๋Œ“๊ธ€์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘์ž…๋‹ˆ๋‹ค.

์•„์ง ๋Œ“๊ธ€์ด ์—†์Šต๋‹ˆ๋‹ค.