INotification
Types
interface INotification<GName extends string, GValue> {
readonly name: GName;
readonly value: GValue;
}
Definition
A Notification is used as a replacement of the next
, complete
and error
events:
you will emit directly a INextNotification
instead of calling subscriber.next()
for example.
To create a Notification, you may use a plain object { name, value }
or use the
function createNotification.
Moreover, you may use some pre-existing Notifications:
Examples
Create an Observable from a Promise
type IObservableFromPromiseNotifications<GValue> =
| INextNotification<GValue>
| ICompleteNotification
| IErrorNotification
;
function fromPromise<GValue>(
promise: Promise<GValue>,
): IObservable<IObservableFromPromiseNotifications<GValue>> {
type GNotificationsUnion = IObservableFromPromiseNotifications<GValue>;
return (emit: IObserver<GNotificationsUnion>): IUnsubscribe => {
let running: boolean = true;
promise
.then(
(value: GValue) => {
if (running) {
emit(createNextNotification<GValue>(value));
}
if (running) {
emit(createCompleteNotification());
}
},
(error: any) => {
if (running) {
emit(createErrorNotification<any>(error));
}
}
);
return (): void => {
running = false;
};
};
}
Consume the notifications
const subscribe = fromPromise(Promise.resolve(5));
subscribe((notification: IObservableFromPromiseNotifications<number>) => {
switch (notification.name) {
case 'next':
console.log('next', notification.value);
break;
case 'complete':
console.log('resolved');
break;
case 'error':
console.log('rejected', notification.value);
break;
}
});
Output:
next: 5
resolved
You may also use the function notificationObserver if you prefer:
subscribe(
notificationObserver({
next: (value: number) => {
console.log('next', value);
},
complete: () => {
console.log('resolved');
},
error: (error: any) => {
console.log('rejected', error);
},
}),
);