RxJS--Subject

Subject是Observable(可观察对象)的子类,subject是多播的,允许将值多播给多个observer(观察者),普通observable是单播。

每一个Subject都是一个Observable(可观察对象),可以订阅(subscribe)它。

要给subject提供新值,只要调用next(theValue), 它会将值theValue多播给已注册监听该subject的观察者们。

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


ngOnInit(){
    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('博客');
    subject.next('圆圆');
    subscriptionA.unsubscribe();    //取消订阅
    subscriptionB.unsubscribe();    //取消订阅
    subject.next('取消订阅后');
    subject.complete();
}

 

每一个Subject也可以作为Observer(观察者),有如下方法:next(v), error(e), complete(); 可以把Subject作为参数传递给任何Observable的subscribe方法

import { Subject,  Subscription, Observable} from 'rxjs';


ngOnInit() {
    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}`);
      }
    );

    const observable: Observable<string> = from(['Raph', 'Don']);
    observable.subscribe(subject);

  }

 

posted @ 2018-11-15 16:08  pei~乐悠悠  阅读(346)  评论(0编辑  收藏  举报