1

https://rxjs-dev.firebaseapp.com/api/ajax/ajax

Why rxjs ajax operator returns an Observable? I think one request gets back one response, and the connection is over. Why is it an Observable instead of a single response message?

Andy Nike
  • 13
  • 2
  • Because the first `A` in `AJAX` stands for "asynchronous". Returning the response message itself would require synchronous behavior. To deal with an asynchronous response, you need something like a callback, a `Promise`, or... an `Observable`. – Robby Cornelissen Mar 30 '20 at 03:38
  • 1
    Thanks. Is this the only reason of Observable return type? That is to say, there will always be one response. We just don't know when it will arrive. – Andy Nike Mar 30 '20 at 03:41
  • With Observables many typical actions on Ajax requests are made simpler. [This answer](https://stackoverflow.com/a/50496692/5699993) has some details. – Picci Mar 30 '20 at 06:50

1 Answers1

0

Any value, whether synchronously available or async, can be represented as an observable.

Rx.of() "lifts" values into a simple observable form - you subscribe and it immediately emits the value(s) you passed to of.

Rx.from() converts certain values (arrays, promises, any iterable) into a logical observable equivalent.

Why are these useful? Because you can do many more things with observables vs other types of values (including promises). For instance you can cancel them if they're async.

Most importantly, it's easier to combine observables with other observables, which is what RxJS is all about.

backtick
  • 2,685
  • 10
  • 18