RXJS Observables - can an observable also be an observer

I am new to rxjs and reactive programming but having read the fundamentals I would like to ask the intelligent community of StackOverflow members if an rxjs Observable can itself be an observer. This happens in practice where for sure an observable can also be an observer. e.g. I observe you the Observable, you observe someone else so you are fulfilling two roles 1) that of observable and also observer. However having said this I cannot quite think of a theoretical example (in maths, science) that can be depicted with rxjs observables! Would someone shed some light on this for me, please?

1 answer

  • answered 2020-08-11 01:21 HongYu

    A Subject is both an Observer and Observable.

    use case:

    import { Component, VERSION, OnInit } from '@angular/core';
    import { interval, Subject } from 'rxjs';
    import { take } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
      name = 'Angular ' + VERSION.major;
    
    
      // Subject demo
      observerA = {
        next: (value) => {
          console.log('observerA', value);
        }
      }
      observerB = {
        next: (value) => {
          console.log('observerB', value);
        }
      }
      subject = new Subject();
      source = interval(1000);
      
      ngOnInit() {
        this.source.pipe(take(10)).subscribe(this.subject);
        this.subject.pipe().subscribe(this.observerA);
        this.subject.pipe().subscribe(this.observerB);
    
      }
    }
    

    output: console.log

    stackblitz

    const { interval, Subject } = rxjs;
    const { take } = rxjs.operators;
    
    const observerA = {
        next: (value) => {
          console.log('observerA', value);
        }
      };
    
    const observerB = {
        next: (value) => {
          console.log('observerB', value);
        }
      };
    
    const subject = new Subject();
    const source = interval(1000);
    
    source.pipe(take(10)).subscribe(subject);
    subject.pipe().subscribe(observerA);
    subject.pipe().subscribe(observerB);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"></script>