What is the equivalent in RxJS to Promise.resolve
? I know I can do Observable.fromPromise(Promise.resolve(someValue));
but there has to be a cleaner way.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
switchMap is one of the most useful RxJS operators because it can compose Observables from an initial value that is unknown or that change. Conceptually, it is similar to chaining then functions with Promises, but operates on streams (Promises resolve once).
the Promise can provide a single value, whereas the Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to the Observable to get a new tailored stream.
Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.
Observable.of is what you are looking for (see this plunk):
// You might need to add this import in RxJS versions earlier than 5 import 'rxjs/add/observable/fromArray'; // ... or this line in RxJS 5+ import 'rxjs/add/observable/of'; if (me.groups) { return Observable.of(me.groups); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With