SHARE
TWEET

Untitled

a guest Mar 20th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Observable<T> {
  2.   private _subscribe: Subscribe<T>;
  3.   private _observers: Identified<Observer<T>>[] = [];
  4.  
  5.   constructor(subscribe?: Subscribe<T>) {
  6.     this._subscribe = subscribe;
  7.   }
  8.  
  9.   subscribe(Observer?: Observer<T>): Subscription;
  10.   subscribe(
  11.     next?: NextObserver<T>,
  12.     error?: ErrorObserver,
  13.     complete?: CompleteObserver
  14.   ): Subscription;
  15.  
  16.   subscribe(
  17.     observer?: Observer<T> | NextObserver<T>,
  18.     error?: ErrorObserver,
  19.     complete?: CompleteObserver
  20.   ): Subscription {
  21.     if (!observer) observer = () => { };
  22.  
  23.     if (!error) error = () => { };
  24.  
  25.     if (!complete) complete = () => { };
  26.  
  27.     let _observer = {} as Identified<Observer<T>>;
  28.  
  29.     _observer.next = value => {
  30.       if (!this._observers.find(({ id }) => _observer.id === id)) return;
  31.       (observer['next'] || observer)(value);
  32.     };
  33.  
  34.     _observer.error = value => {
  35.       if (!this._observers.find(({ id }) => _observer.id === id)) return;
  36.       (observer['error'] || error)(value);
  37.     };
  38.      
  39.     _observer.complete = () => {
  40.       if (!this._observers.find(({ id }) => _observer.id === id)) return;
  41.       this._observers = this._observers.filter(({ id }) => _observer.id !== id);
  42.       (observer['complete'] || complete)();
  43.     };
  44.  
  45.     _observer.id = this._observers.length;  
  46.      
  47.     this._observers.push(_observer);
  48.     this._subscribe(_observer);
  49.  
  50.     return {
  51.       unsubscribe: () =>
  52.         this._observers = this._observers.filter(({ id }) => _observer.id !== id)
  53.     };
  54.   }
  55. }
  56.  
  57. export type Subscribe<T> = (observer: Observer<T>) => Subscription;
  58.  
  59. export type NextObserver<T> = (value?: T) => void;
  60. export type ErrorObserver = (error?: any) => void;
  61. export type CompleteObserver = () => void;
  62.  
  63. export interface Observer<T> {
  64.   next?: NextObserver<T>;
  65.   error?: ErrorObserver;
  66.   complete?: CompleteObserver;
  67. }
  68.  
  69. export type Identified<T> = Partial<T> & { id: any };
  70.  
  71. export interface Subscription {
  72.   unsubscribe(): void;
  73. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top