What is the difference between a Observable and a Subject in rxjs?

前端 未结 8 1046
难免孤独
难免孤独 2020-12-01 00:05

i was going through this blog and to read about Observables and i couldnt figure out the difference between the Observable and a Subject

8条回答
  •  伪装坚强ぢ
    2020-12-01 00:27

    Observables are unicast by design and Subjects are multicast by design.

    if you look at the below example - each subscription recieves the diffrent values as observables developed as unicast by design.

    import {Observable} from 'rxjs';
    
    let obs = Observable.create(observer=>{
       observer.next(Math.random());
    })
    
    obs.subscribe(res=>{
      console.log('subscription a :', res); //subscription a :0.2859800202682865
    });
    
    obs.subscribe(res=>{
      console.log('subscription b :', res); //subscription b :0.694302021731573
    });
    

    this could be weird if you are expecting the same values on both the subscription.

    we can overcome this issue using Subjects. Subjects is similar to event-emitter and it does not invoke for each subscription. consider the below example.

    import {Subject} from 'rxjs';
    
    let obs = new Subject();
    
    obs.subscribe(res=>{
      console.log('subscription a :', res); // subscription a : 0.91767565496093
    });
    
    obs.subscribe(res=>{
      console.log('subscription b :', res);// subscription b : 0.91767565496093
    });
    
    obs.next(Math.random());
    

    both the subscription are got the same output value!.

提交回复
热议问题