DEV Community

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

Collapse
 
amitnovick profile image
Amit Novick • Edited

Hey Johannes! 👋

Never tried Rxjs personally.

Would be cool if you could provide some motivation for why you'd rather use Rxjs async flow instead of Promises, and Rxjs data structures instead of the goold old Array and Object (also the newer Set and Map) from standard JS.

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 :)

Collapse
 
johannesjo profile image
Johannes Millan • Edited

RxJs is really powerful in expressing complex flows with just a couple lines of code. Imagine the above example with timeouts. At least to me it would look a little messy in comparison and the befits start to increase the more complex the code is.

Let me quote from this article: "...it is a powerful tool that turns complicated series of actions into concise code that is easy to manipulate".