rxjs - subject

Posted GoldenaArcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rxjs - subject相关的知识,希望对你有一定的参考价值。

rxjs - subject

暂时学完了,继续搞项目去了


A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.

一个 subject 即像 Observable,又像 EventEmitters;它可以被多个 observers subscribe,同时也维护多个监听器的挂载。

基础 Subject 的用法,注意 Subject 没有初始值,并且在被 subscribe 的时候是无法将当前状态传输到下一个 subscriber 中的。

import  fromEvent, Subject  from 'rxjs';

const emitButton = document.querySelector('button#emit');
const inputElement: htmlInputElement = document.querySelector('#value-input');
const subscribeButton = document.querySelector('button#subscribe');

const value$ = new Subject<string>();

fromEvent(emitButton, 'click').subscribe(() => 
  console.log('emit clicked');
  value$.next(inputElement.value);
);

fromEvent(subscribeButton, 'click').subscribe(() => 
  console.log('new subscription');
  value$.subscribe((value) => console.log(value));
);

如果 subject 出现了异常,那么就会终止所有的 subscription。

BehaviorSubject

A variant of Subject that requires an initial value and emits its current value whenever it is subscribed to.

Subject 的一个变种,需要一个初始值,并且会将当前值传到 subscribe 它的 subscriber 中去。

import  BehaviorSubject, fromEvent  from 'rxjs';
import  withLatestFrom  from 'rxjs/operators';

const loggedInSpan: HTMLElement = document.querySelector('span#logged-in');
const loginButton: HTMLElement = document.querySelector('button#login');
const logoutButton: HTMLElement = document.querySelector('button#logout');
const printStateButton: HTMLElement =
  document.querySelector('button#print-state');

const isLoggedIn$ = new BehaviorSubject<boolean>(false);

fromEvent(loginButton, 'click').subscribe(() => isLoggedIn$.next(true));
fromEvent(logoutButton, 'click').subscribe(() => isLoggedIn$.next(false));

isLoggedIn$.subscribe(
  (isLoggedIn) => (loggedInSpan.innerHTML = isLoggedIn.toString())
);

isLoggedIn$.subscribe((isLoggedIn) => 
  logoutButton.style.display = isLoggedIn ? 'block' : 'none';
  loginButton.style.display = !isLoggedIn ? 'block' : 'none';
);

fromEvent(printStateButton, 'click')
  .pipe(withLatestFrom(isLoggedIn$))
  .subscribe(([event, isLoggedin]) =>
    console.log('User is logged in:', isLoggedin)
  );

以上是关于rxjs - subject的主要内容,如果未能解决你的问题,请参考以下文章

Angular RXJS Observables或Subjects在内部传递数字

rxjs - 主题订阅者错过了一个值

找不到模块 'rxjs/subject/BehaviorSubject'

rxjs - subject

rxjs - subject

在多个函数中重用一个rxjs'主题