Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nicolae-olariu/3de0998204430e50dcd0e0ea0b2aaa0e to your computer and use it in GitHub Desktop.
Save nicolae-olariu/3de0998204430e50dcd0e0ea0b2aaa0e to your computer and use it in GitHub Desktop.
simulate pattern observable in vanilla JS

Rxjs

const next = (message)=> console.log("First observer message: " + message);
const error = (error) => console.log("Second observer error: " + error);
const complete = () => console.log("complete");

const next1 = (message)=> console.log("First observer message 1: " + message);
const error1 = (error) => console.log("Second observer error 1: " + error);
const complete1 = () => console.log("complete 1");

const stream$ = Rx.Observable.of(1,2,3,4,5)

stream$.subscribe(next, error, complete)
stream$.subscribe(next1, error1, complete1)

Vanilla JS

function ObservableOf(...data) {
    this.subscribe =  function(...observer) {
      const [next,error,complete] = observer
      observerD = {next, error, complete };
      
      try{
        data.forEach((item)=> {
          //simulated an error with the type
          if(typeof item  === 'string'){
            throw {};
          }
          observerD.next(item)
        });
        observerD.complete();
      }catch(e){
        observerD.error("is a string");
      }
    };
    
    return {subscribe: this.subscribe}
}

const source$ = new ObservableOf(1,"2",3)

source$.subscribe(
     (message) => console.log("First observer message:" + message),
     (error) => console.log("First observer error:" + error),
     () => console.log("complete First")
)

source$.subscribe(
    (message) => console.log("Second observer message:" + message), 
    (error) => console.log("Second observer error:" + error),
    () => console.log("complete Second")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment