Skip to main content

unknownToObservable

Types

function unknownToObservable<GInput>(
input: GInput,
): IUnknownToObservable<GInput, 'not-undefined'>;
function unknownToObservable<GInput, GMode extends IUnknownToObservableMode>(
input: GInput,
mode: GMode,
): IUnknownToObservable<GInput, GMode>;
function unknownToObservable<GInput, GMode extends IUnknownToObservableMode>(
input: GInput,
mode: GMode = 'not-undefined' as GMode,
): IUnknownToObservable<GInput, GMode>

Definition

Converts an Observable, a Signal or any other value into an Observable.

If the input is a Signal, we return fromSignal(input) Else, if the input is a function, we assume it's an Observable and return it. Finally, if the input is none of the above we return single(value).

This is useful in some cases, when you want to create a function that accepts an Observable, a Signal or directly a value as input.

The mode if used to determine what to do when a raw value is provided as input:

  • strict: raw values are forbidden, and we throw an Error.
  • not-undefined (default): all values are accepted, except undefined.
  • any (default): all values are accepted.

Alternatives

unknownToObservableNotUndefined

function unknownToObservableNotUndefined<GInput>(
input: GInput,
): IUnknownToObservableNotUndefined<GInput>

Alias for unknownToObservable with mode: 'not-undefined'.

unknownToObservableStrict

function unknownToObservableStrict<GInput>(
input: GInput,
): IUnknownToObservableStrict<GInput>

Alias for unknownToObservable with mode: 'strict'.

Example

Creates an Observable formatting a number or an Observable of number to a string

export function formatNumberObservable(
input: IObservableLike<number>,
): IObservable<string> {
return map$$(unknownToObservable(input), (value: number): string => {
return new Intl.NumberFormat(navigator.languages).format(value);
});
}

From an Observable

const subscribe = unknownToObservable(of(1, 2, 3));

subscribe((value: number) => {
console.log(value);
});

Output:

1
2
3

From a number

const subscribe = unknownToObservable(4);

subscribe((value: number) => {
console.log(value);
});

Output:

4

Throws if undefined

let value!: number;
const subscribe = unknownToObservableNotUndefined(value); // throws an error
value = 4; // oops, value initialized too late

subscribe((value: number) => {
console.log(value);
});

Output:

TypeError(`Not an observable`)