Subject theme of RxJS (Angular environment)

A Subject

Subject is a subclass of Observable. Subjects are multicast, allowing values ​​to be multicast to multiple observers. Ordinary Observables are unicast.

Inside the Subject, subscribe the new implementation that sends the value is not called. It just registers the given observer to the list of observers, similar to how it  addListener works in other libraries or languages.

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-subject',
  templateUrl: './subject.component.html',
  styleUrls: ['./subject.component.css']
})
export class SubjectComponent implements OnInit {

  constructor() { }

  by OnInit () {
    const subject: Subject<string> = new Subject<string>();
    const subscriptionA: Subscription = subject.subscribe(
      (val: string) => {
        console.log(`observerA: ${val}`);
      }
    );
    const subscriptionB: Subscription = subject.subscribe(
      (val: string) => {
        console.log(`observerB: ${val}`);
      }
    );
    subject.next('Mikey');
    subject.next('Leo');
    subscriptionA.unsubscribe(); // unsubscribe 
    subscriptionB.unsubscribe(); // unsubscribe 
    subject.next( 'Raph' );
    subject.complete();
  }

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325280707&siteId=291194637