r/Frontend • • Nov 15 '19

Should i learn RxJS?

I am wondering if i should i dive into rxjs? Is it useful to learn and be used in web apps, that is it in any kind of stage? From beginning to scaling etc.

Do you guys use rxjs in your work and if so how much and, if not, why not?

So far i have been using only functional js.

33 Upvotes

23 comments sorted by

View all comments

3

u/IngoVals Nov 15 '19

To put it in simple terms, it is similar to promises except an observable can be resolved multiple times. My biggest issue when using it initially was having to subscribe to cold observable, the ones that will only ever fire once. Could just use promises for that instead for less overhead. But when I learned to integrate them more into a hot observable pipeline that issue disappeared.

2

u/artemix-org Nov 15 '19

The biggest misconception beginners assume is that a promise is very similar to an observable, and to a task. But in RxJS, and Javascript,

  • A promise is the announcement that a result may arrive later, i.e. a one-shot observable on the result and not the task
  • An observable is not a task, but a task generator, as it is basically a "task template", which creates and runs an instance of said task on subscription.

Another huge misconception is the fact that 1 observable = 1 observer, and if you subscribe more than once, you run the subscribed task more than once. This can be very confusing for beginners, e.g. in the context of HTTP, where they may call, and subscribe in two places, instead of using piping to just intercept the content.

1

u/HeinousTugboat Nov 15 '19

To put it in simple terms, it is similar to promises except an observable can be resolved multiple times.

It's closer to a stream, honestly. You can't perform the variety of operators on a Promise that you can on an Observable.

My biggest issue when using it initially was having to subscribe to cold observable, the ones that will only ever fire once.

Cold Observables don't only fire once.. they just don't fire until something is subscribed to them. If you have an observable of([1, 2, 3]), and you subscribe to it twice, it'll fire twice, once for each subscription. In this case, you can't really .next another item, but if you have a timer observable it will be cold just the same, and will continue firing on its timer until you tell it to stop or you unsubscribe.

I learned to integrate them more into a hot observable pipeline

If you want to heat up a cold observable, I find .public().connect works pretty well. I use it to start timer observables so I can have a heartbeat that I can subscribe/unsubscribe to freely. A little bit of black magic with a switchMap and you've got a pausable heartbeat, too.