tiny observable implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Subscription { | |
readonly closed: boolean; | |
unsubscribe: () => void; | |
} | |
export interface Observer<T> { | |
closed: boolean; | |
error: (error: any) => void; | |
complete: () => void; | |
next: (value: T) => void; | |
} | |
export type SubscriberFunction<T> = ( | |
observer: Observer<T>, | |
) => { unsubscribe: () => void } | void; | |
export default class Observable<T> { | |
private _subscribe: SubscriberFunction<T>; | |
public constructor(subscribe: SubscriberFunction<T>) { | |
this._subscribe = subscribe; | |
} | |
subscribe( | |
nextOrObserver: Partial<Observer<T>> | ((value?: T) => void), | |
error?: (errorValue: Error) => void, | |
complete?: () => void, | |
) { | |
let closed = false; | |
const observer = | |
typeof nextOrObserver === 'function' | |
? { next: nextOrObserver, error, complete } | |
: nextOrObserver; | |
// eslint-disable-next-line prefer-const | |
let subscriber: void | { unsubscribe: () => void }; | |
const subscription: Subscription = { | |
get closed() { | |
return closed; | |
}, | |
unsubscribe() { | |
if (closed) return; | |
closed = true; | |
subscriber?.unsubscribe(); | |
}, | |
}; | |
subscriber = this._subscribe({ | |
closed, | |
error(err?: any) { | |
if (closed) return; | |
subscription.unsubscribe(); | |
observer.error?.(err); | |
}, | |
complete() { | |
if (closed) return; | |
try { | |
subscription.unsubscribe(); | |
observer.complete?.(); | |
} catch (err) { | |
subscription.unsubscribe(); | |
observer.error?.(err); | |
} | |
}, | |
next(value: T) { | |
if (closed) return; | |
try { | |
observer.next?.(value); | |
} catch (err) { | |
subscription.unsubscribe(); | |
observer.error?.(err); | |
} | |
}, | |
}); | |
return subscription; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples of use