Rxjs: shorthand of create observable from value or observable

dvl Batdelger

I'm using rxjs with typescript. I wrote following two simple functions. But I guess rxjs already has such functionality. Does rxjs?

export function isObservable(value: any): value is Observable<any> {
  return value instanceof Observable;
}

export function createObservable<T>(value: T | Observable<T>): Observable < T > {
  return isObservable(value) ? value : Observable.of(value);
}
martin

I don't think RxJS 5 has exactly this functionality already because it's you who should be aware of what type of data you're working with.

However, you can make use of the fact that RxJS handles any Observables, Promises, Observable-like, array-like and so on ... objects the same way and write the following:

const val1 = Observable.of(42);
const val2 = [42];

Observable.from(val1).subscribe(console.log);
Observable.from(val2).subscribe(console.log);

This will in both cases print just 42 even though once I used an Observable with a single value and then an array with a single value.

See live demo: https://jsbin.com/fubobon/3/edit?js,console

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

RxJs get value from observable

RxJS: Observable.create() vs. Observable.from()

RxJs Observable in Observable from Array

RxJs Create Observable from resulting Promise

How to create an RxJs Observable from a node request

RxJS: Setting default value for observable from another observable

Problem returning value from RxJS Observable

RXJS Create Observable for sockets

Difference in importing Observable from 'rxjs/Observable' and 'rxjs'

How to create an Observable that depends on another Observable in RxJS

Rxjs: Create Observable that is a delayed offset of another observable

RxJS wait for observable then create another observable, and so on

RxJS Observable result from an Observable's output

Returning a Property from Observable as Observable in Rxjs Angular

How to create a waterfall observable in rxjs?

Rxjs combinelatest observable value is undefined

Best way to create Observable, using from, in RxJS 5.x?

How to create an rxjs Observable from TextInput (either onChange or onTextChange)

RxJS create new Observable "Array" from and static array in typescript

How can i get value from an Rxjs observable in my code?

Using RXJS to extract single value from observable with no mutation

Mapping Key Value Pair from request using RxJS and observable

How to use the value from an RxJS observable subscribe call

Javascript rxjs - do something when last value emitted from observable

Angular RxJS Copy Value from One Element to Next in Observable Array

Return a Observable from a Subscription with RxJS

RxJs Observable from backed with pulling

Immediately unsubscribing from RxJS Observable

RXJS observable in observable