본문 바로가기
JavaScript TypeScript

[RxJS - 4] pipe(), map()

by Nhahan 2023. 10. 6.
function createHttpObservable(url: string) 
  return Observable.create(observer => {
    fetch(url)
      .then(response => {
    
        return response.json();
      
      })
      .then(body => {
    
        observer.next(body); // Subscriber에게 데이터 전달
        observer.complete(); // 데이터 전달 완료
      
      })
      .catch(err => {
    
        observer.error(err);
      
      })
});

위와 같은 Observable 객체를 만드는 함수가 있다고 하자.

 

pipe()는 Observable 객체를 새로운 Observable 객체로 만들어준다. 그리고

map()은 우리가 알고 있는 그 map과 동일하다.

const http$ = createHttpObservable('/api');
/*
{
  "items": [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"},
    {"id": "ViewSource", "label": "View Source"},
  ]
}
*/

const items$ = https$
    .pipe(
      map(res -=> Object.values(res['items']))
    );

// items$는 Observable이므로 subscribe할 수 있다.
items$.subscribe(
    items => console.log(items),
    err => console.log(err)
    () => console.log("finished!")
);
/*
[
  {"id": "Open"},
  {"id": "OpenNew", "label": "Open New"},
  {"id": "Find", "label": "Find..."},
  {"id": "FindAgain", "label": "Find Again"},
  {"id": "Copy"},
  {"id": "CopyAgain", "label": "Copy Again"},
  {"id": "CopySVG", "label": "Copy SVG"},
  {"id": "ViewSVG", "label": "View SVG"},
  {"id": "ViewSource", "label": "View Source"},
]
*/

subscribe() 안에는 필수적이고 핵심인 로직을 담고, 그 전에 pipe()와 map()을 이용하여 데이터를 전처리한다고 생각하면 된다.

댓글