Ver3.5 ๐ RxJS์ ํ์ ์คํฌ๋ฆฝํธ: ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ ๊ตฌํ

๐ RxJS์ ํ์ ์คํฌ๋ฆฝํธ: ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ ๊ตฌํ
๋ฐ์ดํฐ ์คํธ๋ฆผ์ ์์ ์์ฌ๋ก ๋ค๋ฃจ๋ ๋ฆฌ์กํฐ๋ธ ํ๋ก๊ทธ๋๋ฐ์ ์ธ๊ณ๋ก ๐
์์งํ ๋งํ๋ฉด, ์ฒ์ "๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ(Reactive Programming)"์ด๋ผ๋ ๋ง์ ๋ค์์ ๋ ๋ญ๊ฐ ์์ฒญ ๋ณต์กํ ๊ฐ๋ ๊ฐ์์ ์ง๋ ๊ฒ๋จน๋ ๋ถ๋ค์ด ๋ง์์. ๊ทผ๋ฐ ์ฌ์ค ๊ฐ๋ ์์ฒด๋ ์๊ฐ๋ณด๋ค ์ง๊ด์ ์ด์์! ๐
์ฝ๊ฒ ์ค๋ช ํ๋ฉด ์ด๋ ์ต๋๋ค. ์ฐ๋ฆฌ๊ฐ ์ผ๋ฐ์ ์ผ๋ก ์ฝ๋๋ฅผ ์งค ๋๋ "์ด ๊ฐ์ ๊ฐ์ ธ์์, ์ฒ๋ฆฌํ๊ณ , ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํด" ๊ฐ์ ๋ช ๋ นํ ๋ฐฉ์์ ์จ์. ๋ฐ๋ฉด ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ์ "์ด ๋ฐ์ดํฐ ์คํธ๋ฆผ์ ๊ตฌ๋ ํ๊ณ ์๋ค๊ฐ, ๋ญ๊ฐ ํ๋ฌ์ค๋ฉด ๊ทธ๋ ์ฒ๋ฆฌํด" ๋ผ๋ ๋ฐฉ์์ด์์.
์๋ฅผ ๋ค์ด๋ณผ๊ฒ์. ์์
์คํ๋ ๋์ํธ ์๊ฐํด๋ณด์ธ์. A1 ์
์ ์ซ์๋ฅผ ๋ฃ๊ณ , B1 ์
์ =A1*2 ๋ผ๊ณ ์
๋ ฅํ๋ฉด, A1 ๊ฐ์ด ๋ฐ๋ ๋๋ง๋ค B1๋ ์๋์ผ๋ก ๋ฐ๋์์์? ์ด๊ฒ ๋ฐ๋ก ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ์ ํต์ฌ ์์ด๋์ด์์! ๐ฏ
์น ๊ฐ๋ฐ์์๋ ์ด๋ฐ ์ํฉ๋ค์ด ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ๊ณผ ๋ฑ ๋ง์์:
ํด๋ฆญ, ํค๋ณด๋ ์ ๋ ฅ, ๋ง์ฐ์ค ์์ง์ ๋ฑ ์ฐ์์ ์ผ๋ก ๋ฐ์ํ๋ ์ด๋ฒคํธ๋ค
๋น๋๊ธฐ API ํธ์ถ, ์ค์๊ฐ ๋ฐ์ดํฐ ํด๋ง, WebSocket ์ฐ๊ฒฐ
์ฃผ๊ธฐ์ ์ผ๋ก ๋ฐ์ํ๋ ์ด๋ฒคํธ, ์ ๋๋ฉ์ด์ ํ๋ ์
๊ฒ์์ฐฝ์ ํ์ดํํ ๋๋ง๋ค 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 ํธ์ถ๋จ, ์ด์ ์์ฒญ ์ทจ์ ๋ถ๊ฐ, ์์ ๋ณด์ฅ ์๋จ
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(Reactive Extensions for JavaScript)๋ ๋ง์ดํฌ๋ก์ํํธ๊ฐ ๋ง๋ ReactiveX ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ JavaScript ๋ฒ์ ์ด์์. ํ์ฌ ๋ฒ์ 7.x๊ฐ ์์ ๋ฒ์ ์ด๊ณ , Angular ํ๋ ์์ํฌ์์๋ ๊ธฐ๋ณธ์ผ๋ก ํ์ฌ๋์ด ์์ ๋งํผ ์ค๋ฌด์์ ๋ง์ด ์ฐ์ด๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์.
Observable์ RxJS์ ํต์ฌ ์ค์ ํต์ฌ์ด์์. ์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ์ฌ๋ฌ ๊ฐ์ ๋ฐฉ์ถ(emit)ํ ์ ์๋ ๊ฒ์ผ๋ฅธ(lazy) ๋ฐ์ดํฐ ์คํธ๋ฆผ์ด๋ผ๊ณ ์๊ฐํ๋ฉด ๋ผ์.
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๋ Observable์ด ๋ฐฉ์ถํ๋ ๊ฐ์ ๋ฐ์์ ์ฒ๋ฆฌํ๋ ๊ฐ์ฒด์์. ์ธ ๊ฐ์ง ์ฝ๋ฐฑ์ผ๋ก ๊ตฌ์ฑ๋ฉ๋๋ค:
| ์ฝ๋ฐฑ | ์ญํ | ํธ์ถ ์์ |
|---|---|---|
next |
์ ์ ๊ฐ ์ฒ๋ฆฌ | Observable์ด ๊ฐ์ ๋ฐฉ์ถํ ๋๋ง๋ค |
error |
์๋ฌ ์ฒ๋ฆฌ | ์๋ฌ ๋ฐ์ ์ (์ดํ ์คํธ๋ฆผ ์ข ๋ฃ) |
complete |
์๋ฃ ์ฒ๋ฆฌ | ์คํธ๋ฆผ์ด ์ ์ ์ข ๋ฃ๋ ๋ |
Subject๋ RxJS์์ ํน๋ณํ ์กด์ฌ์์. Observable์ด๋ฉด์ ๋์์ Observer์ด๊ธฐ๋ ํด์. ์ฆ, ๊ฐ์ ๋ฐฉ์ถํ ์๋ ์๊ณ , ๋ค๋ฅธ Observable์ ๊ตฌ๋ ํ ์๋ ์์ด์. ๋ฉํฐ์บ์คํ (์ฌ๋ฌ ๊ตฌ๋ ์์๊ฒ ๋์์ ๊ฐ ์ ๋ฌ)์ด ๊ฐ๋ฅํ ๊ฒ ํต์ฌ ํน์ง์ด์์!
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
์ด๊ธฐ๊ฐ์ ๊ฐ์ง๋ฉฐ, ์ ๊ตฌ๋ ์์๊ฒ ๋ง์ง๋ง ๊ฐ์ ์ฆ์ ์ ๋ฌ. ์ํ ๊ด๋ฆฌ์ ์ต์ !
์ง์ ํ ๊ฐ์๋งํผ ์ด์ ๊ฐ๋ค์ ๋ฒํผ๋งํด์ ์ ๊ตฌ๋ ์์๊ฒ ์ฌ์ ์ก
complete() ํธ์ถ ์ ๋ง์ง๋ง ๊ฐ๋ง ๊ตฌ๋ ์์๊ฒ ์ ๋ฌ
subscribe()๋ฅผ ํธ์ถํ๋ฉด Subscription ๊ฐ์ฒด๊ฐ ๋ฐํ๋ผ์. ์ด๊ฑธ ํตํด ๊ตฌ๋ ์ ํด์ (unsubscribe)ํ ์ ์์ด์. ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฐฉ์ง๋ฅผ ์ํด ๋ฐ๋์ ๊ตฌ๋ ํด์ ๋ฅผ ํด์ค์ผ ํด์! ํนํ ์ปดํฌ๋ํธ๊ฐ ์๋ฉธ๋ ๋์.
import { interval } from 'rxjs';
const subscription = interval(1000).subscribe(val => {
console.log('๋งค์ด๋ง๋ค:', val);
});
// 5์ด ํ ๊ตฌ๋
ํด์
setTimeout(() => {
subscription.unsubscribe();
console.log('๊ตฌ๋
ํด์ ๋จ!');
}, 5000);
RxJS ์์ฒด๋ ํ๋ฅญํ์ง๋ง, TypeScript์ ํจ๊ป ์ฐ๋ฉด ์ง์ง ๋ ๊ฐ๋ฅผ ๋ฌ์์! ๐ฆ ํ์ ์์ ์ฑ์ด ๋ณด์ฅ๋๋๊น ๋ฐํ์ ์๋ฌ๋ฅผ ์ปดํ์ผ ํ์์ ์ก์ ์ ์๊ฑฐ๋ ์.
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)); // ํ์
์์ !
});
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}์`));
});
$๋ฅผ ๋ถ์ด๋ ๊ฑด RxJS ์ปค๋ฎค๋ํฐ์ ๊ด๋ก์์. users$, products$ ์ฒ๋ผ์. ์ด๋ ๊ฒ ํ๋ฉด ์ฝ๋์์ Observable์ธ์ง ์ผ๋ฐ ๋ณ์์ธ์ง ํ๋์ ๊ตฌ๋ถํ ์ ์์ด์!
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์๋ 100๊ฐ๊ฐ ๋๋ ์คํผ๋ ์ดํฐ๊ฐ ์๋๋ฐ, ์ฒ์๋ถํฐ ๋ค ์ธ์ฐ๋ ค๊ณ ํ๋ฉด ๋จธ๋ฆฌ๊ฐ ํฐ์ ธ์ ๐ฅ. ์ค๋ฌด์์ ์์ฃผ ์ฐ์ด๋ ํต์ฌ ์คํผ๋ ์ดํฐ๋ค๋ง ์ ๋๋ก ์ดํดํ๋ฉด ์ถฉ๋ถํด์!
๋ฐฐ์ด์ 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 }))
);
์ด ๋ค ๊ฐ์ง๋ RxJS์์ ๊ฐ์ฅ ํท๊ฐ๋ฆฌ๋ ์คํผ๋ ์ดํฐ๋ค์ด์์. ๋ชจ๋ "Observable์ ๋ฐํํ๋ ํจ์"๋ฅผ ์ธ์๋ก ๋ฐ๋๋ฐ, ๋์ ๋ฐฉ์์ด ๋ฌ๋ผ์!
| ์คํผ๋ ์ดํฐ | ์ ์์ฒญ ์์ ๋ | ์ฃผ์ ์ฌ์ฉ ์ฌ๋ก |
|---|---|---|
switchMap |
์ด์ ์์ฒญ ์ทจ์, ์ ์์ฒญ ์คํ | ๊ฒ์ ์๋์์ฑ, ์ต์ ๊ฐ๋ง ํ์ํ ๋ |
mergeMap |
์ด์ ์์ฒญ ์ ์ง, ๋ณ๋ ฌ ์คํ | ๋ ๋ฆฝ์ ์ธ ๋ณ๋ ฌ ์์ฒญ, ์์ ๋ฌด๊ด |
concatMap |
์ด์ ์์ฒญ ์๋ฃ ํ ์์๋๋ก ์คํ | ์์๊ฐ ์ค์ํ ์์ , ํ์ผ ์ ๋ก๋ |
exhaustMap |
์ด์ ์์ฒญ ์งํ ์ค์ด๋ฉด ์ ์์ฒญ ๋ฌด์ | ๋ก๊ทธ์ธ ๋ฒํผ, ์ค๋ณต ์ ์ถ ๋ฐฉ์ง |
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);
// ์ด์ ๊ฒ์ ์์ฒญ์ ์๋์ผ๋ก ์ทจ์๋จ!
});
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)
});
// ๋ก๊ทธ์ธ ์์ฒญ ์ค์ ๋ฒํผ์ ์๋ฌด๋ฆฌ ๋๋ฌ๋ ์ค๋ณต ์์ฒญ ์ ๋จ!
์ฌ๋ฌ Observable์ ์ต์ ๊ฐ์ ๊ฒฐํฉํ ๋ ์ฌ์ฉํด์. ๋ชจ๋ Observable์ด ์ต์ ํ ๋ฒ์ฉ ๊ฐ์ ๋ฐฉ์ถํ ํ๋ถํฐ ๋์ํด์.
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');
Promise.all()๊ณผ ๋น์ทํ ๊ฐ๋ ์ด์์. ์ฌ๋ฌ Observable์ด ๋ชจ๋ ์๋ฃ๋ ๋๊น์ง ๊ธฐ๋ค๋ ธ๋ค๊ฐ ๋ง์ง๋ง ๊ฐ๋ค์ ํ ๋ฒ์ ๋ฐฉ์ถํด์.
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);
});
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)
});
์ด๋ก ์ ์ถฉ๋ถํ ๋ดค์ผ๋, ์ด์ ์ค์ ํ๋ก์ ํธ์์ ์ด๋ป๊ฒ ํ์ฉํ๋์ง ์ดํด๋ด์! ์ฌ๋ฅ๋ท ๊ฐ์ ํ๋ซํผ์ ๋ง๋ ๋ค๊ณ ๊ฐ์ ํ๊ณ ์ค์ ์์ ๋ฅผ ์์ฑํด๋ณผ๊ฒ์. ๐ฏ
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';
});
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);
});
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);
});
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);
});
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 ๋ชจ๋ ๊ฐ์ ๋ฐ์ดํฐ ๋ฐ์
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() ์ค ์ํฉ์ ๋ง๋ ๋ฐฉ๋ฒ์ ๋ฐ๋์ ์ฌ์ฉํ์ธ์.
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๋ ๋ง๋ธ ํ ์คํ (Marble Testing)์ด๋ผ๋ ๋ ํนํ ๋ฐฉ๋ฒ์ ์ ๊ณตํด์!
๋ง๋ธ ๋ค์ด์ด๊ทธ๋จ์ ์๊ฐ ์ถ ์์ ์ด๋ฒคํธ๋ฅผ ํํํ๋ ๋ฐฉ๋ฒ์ด์์. ๋ฌธ์๋ก ํํํ๋ฉด ์ด๋ ๊ฒ ์๊ฒผ์ด์:
--a--b--c--|- : 10ms ๊ฒฝ๊ณผa, b, c : ๊ฐ ๋ฐฉ์ถ| : ์๋ฃ# : ์๋ฌ^ : ๊ตฌ๋
์์์
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();
}
});
});
});
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);
โข ๊ฒ์/์๋์์ฑ โ
switchMap (์ต์ ์์ฒญ๋ง ์ ํจ)โข ํ์ผ ์ ๋ก๋ ํ โ
concatMap (์์ ๋ณด์ฅ)โข ๋ ๋ฆฝ์ ๋ณ๋ ฌ ์์ฒญ โ
mergeMap (๋์ ์คํ)โข ์ค๋ณต ํด๋ฆญ ๋ฐฉ์ง โ
exhaustMap (์งํ ์ค์ด๋ฉด ๋ฌด์)
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);
});
{
"compilerOptions": {
"strict": true, // ์๊ฒฉ ๋ชจ๋ ํ์ฑํ
"strictNullChecks": true, // null/undefined ์ฒดํฌ
"noImplicitAny": true, // any ํ์
์๋ฌต์ ์ฌ์ฉ ๊ธ์ง
"strictFunctionTypes": true,
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"moduleResolution": "node"
}
}
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 # ํ์
๊ฐ๋
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);
}
}
์ปดํฌ๋ํธ๊ฐ ์๋ฉธ๋ ๋ ๊ตฌ๋
์ ํด์ ํ์ง ์์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ ๋์๊ฐ ๋ฐ์ํด์. takeUntil(destroy$) ํจํด์ ๋ฐ๋์ ์ฌ์ฉํ์ธ์!
subscribe ์์ ๋ subscribe๋ฅผ ๋ฃ๋ ๊ฑด ์ฝ๋ฐฑ ์ง์ฅ๊ณผ ๊ฐ์์. switchMap, mergeMap ๋ฑ ๊ณ ์ฐจ ์คํผ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ธ์!
์๋ฌ ํธ๋ค๋ฌ ์์ด ๊ตฌ๋
ํ๋ฉด ์๋ฌ ๋ฐ์ ์ ์คํธ๋ฆผ์ด ์ข
๋ฃ๋๊ณ ์ฑ์ด ๋ฉ์ถ ์ ์์ด์. ํญ์ catchError๋ฅผ ์ฌ์ฉํ๊ฑฐ๋ subscribe์ error ์ฝ๋ฐฑ์ ์ง์ ํ์ธ์!
๊ฐ์ HTTP ์์ฒญ Observable์ ์ฌ๋ฌ ๋ฒ ๊ตฌ๋
ํ๋ฉด ์์ฒญ์ด ์ฌ๋ฌ ๋ฒ ๋ฐ์ํด์. shareReplay(1)๋ก ์บ์ฑํ๊ฑฐ๋ Subject๋ฅผ ์ฌ์ฉํ์ธ์!
TypeScript๋ฅผ ์ฐ๋ ์ด์ ๊ฐ ํ์
์์ ์ฑ์ธ๋ฐ, any๋ฅผ ๋จ์ฉํ๋ฉด ์๋ฏธ๊ฐ ์์ด์. ์ ๋ค๋ฆญ๊ณผ ์ธํฐํ์ด์ค๋ฅผ ์ ๊ทน ํ์ฉํ์ธ์!
์ฒ์ ์์ํ๋ ๋ถ๋ค์ ์ํ ๋จ๊ณ๋ณ ํ์ต ๊ฐ์ด๋์์! ๋จ๊ณ๋ฅผ ๊ฑด๋๋ฐ์ง ๋ง๊ณ ์ฐจ๊ทผ์ฐจ๊ทผ ๋ฐ๋ผ๊ฐ๋ฉด ์ด๋์ RxJS ๊ณ ์๊ฐ ๋์ด ์์ ๊ฑฐ์์ ๐ช
์, ์ฌ๊ธฐ๊น์ง RxJS์ TypeScript๋ฅผ ์ด์ฉํ ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ์ ๋ํด ๊ฝค ๊น๊ฒ ์ดํด๋ดค์ด์! ์ฒ์์ Observable, Subject, ์คํผ๋ ์ดํฐ๋ค์ด ๋ฏ์ค๊ณ ๋ณต์กํด ๋ณด์ด์ง๋ง, ํต์ฌ ๊ฐ๋ ๋ช ๊ฐ์ง๋ง ์ ๋๋ก ์ดํดํ๋ฉด ๋๋จธ์ง๋ ์์ฐ์ค๋ฝ๊ฒ ๋ฐ๋ผ์์ ๐
Observable ๋ฐ์ดํฐ ์คํธ๋ฆผ์ ์์์ , ๊ตฌ๋ ์ ๊น์ง ์คํ ์ ๋จ
Subject Observable + Observer, ๋ฉํฐ์บ์คํ ๊ฐ๋ฅ
pipe() ์คํผ๋ ์ดํฐ ์ฒด์ด๋์ผ๋ก ๋ฐ์ดํฐ ๋ณํ
TypeScript ์ ๋ค๋ฆญ์ผ๋ก ํ์ ์์ ํ ์คํธ๋ฆผ ์ฒ๋ฆฌ
๊ตฌ๋ ํด์ takeUntil, unsubscribe๋ก ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฐฉ์ง
RxJS๋ฅผ ์ฒ์ ๋ฐฐ์ธ ๋ ๊ฐ์ฅ ์ข์ ๋ฐฉ๋ฒ์ ์์ ๊ฒ๋ถํฐ ์ง์ ๋ง๋ค์ด๋ณด๋ ๊ฒ์ด์์. ํ์ด๋จธ ์ฑ, ๊ฒ์ ์๋์์ฑ, ์ค์๊ฐ ์๋ฆผ ๊ฐ์ ์์ ํ๋ก์ ํธ๋ถํฐ ์์ํด์ ์ ์ ๋ณต์กํ ๊ธฐ๋ฅ์ผ๋ก ํ์ฅํด๋๊ฐ๋ฉด ๋ผ์.
๋ง์ฝ RxJS๋ TypeScript ๊ด๋ จ ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ ๋์์ด ํ์ํ๋ค๋ฉด, ์ฌ๋ฅ๋ท์์ TypeScript/RxJS ์ ๋ฌธ๊ฐ๋ฅผ ์ฐพ์๋ณด๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ด์์! ๋ค์ํ ๊ฐ๋ฐ ์ฌ๋ฅ์ ๊ฐ์ง ๋ถ๋ค์ด ์ฌ๋ฌ๋ถ์ ํ๋ก์ ํธ๋ฅผ ๋์์ค ์ ์๊ฑฐ๋ ์ ๐ค
๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ์ ์ฒ์์ ํจ๋ฌ๋ค์ ์ ํ์ด ํ์ํด์ ์ด๋ ต๊ฒ ๋๊ปด์ง์ง๋ง, ํ ๋ฒ ์ต์ํด์ง๋ฉด ๋ณต์กํ ๋น๋๊ธฐ ๋ก์ง์ ํจ์ฌ ์ฐ์ํ๊ฒ ์ฒ๋ฆฌํ ์ ์์ด์. ํนํ TypeScript์ ํจ๊ป ์ฐ๋ฉด ํ์ ์์ ์ฑ๊น์ง ๋ณด์ฅ๋๋๊น, ๋๊ท๋ชจ ํ๋ก์ ํธ์์ ์ง๊ฐ๋ฅผ ๋ฐํํด์! ๐ช
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.