본문 바로가기
JavaScript TypeScript

[RxJS - 3] Observable 생성

by Nhahan 2023. 9. 26.
fetch('/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"},
  ]
}
*/

위와 같은 API가 있다고 가정했을 때, `fetch('/api')`는 Promise를 반환하게 된다. 이를 Observable 객체로 다뤄보자.

 

const http$ = Observable.create(observer => {
  fetch('/api')
    .then(response => {
    
      return response.json();
      
    })
    .then(body => {
    
      observer.next(body); // Subscriber에게 데이터 전달
      observer.complete(); // 데이터 전달 완료
      
    })
    .catch(err => {
    
      observer.error(err);
      
    })
});

console.log(http$); // 아무것도 로깅되지 않음.

위처럼 http$라는 Observable객체를 만들고, console.log(http$)를 해도 아무것도 찍히지 않는다.

왜냐하면 subscribe하지 않았기 때문이다.

 

http$.subscribe(
  items => console.log(items),
  () => {},
  () => console.log('finished!')
)

/* console.log(items)
{
  "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"},
  ]
}
*/

subscribe 후, 데이터를 확인가능해졌다.

 

댓글