DEV Community

Discussion on: What's the RxJs/ NgRx code bit that you are most proud of?

Collapse
 
spiralx profile image
James Skinner

You would use a Promise for an asynchronous task that is run once and either completes or fails, and an Observable for an asynchronous task that runs and can keep producing new results - it may or may not have a point at which it is completed depending on the task. A Promise is the asynchronous version of a callback, and an Observable is the asynchronous version of a stream.

fromEvent(filterElem, 'input').pipe(
  map(event => event.target.value),
  filter(value => value.length > 3),
  debounceTime(1000),
  switchMap(async value => {
    try {
      const response = await(`http://foo.com/items?filter=${value}`)
      const data = await response.json()
      return { error: null, items: data.items }
    } catch (error) {
      console.warn(error)
      return { error, items: [] }
    }
  })
).subscribe(({ error, items }) => {
  // display items/error
})

The above code calls an API to get a filtered list of items whenever the input element changes, as long as it's at least 3 characters long, and at most once a second, and cancelling any existing request that's still in progress if a new one starts. Note that I've used a Promise for doing the fetch API call and processing the response :)