What's the point of AsyncSubject in RXJS?

后端 未结 2 1088

The documentation for RxJS defines AsyncSubject as follows:

The AsyncSubject is a variant where only the last value of the O

2条回答
  •  盖世英雄少女心
    2021-01-11 12:39

    Cool!

    And just for fun, I added handlers to log complete events to show they are raised in either case (Subject or AsyncSubject) when a subscribe happens after a subject is completed.

    Also added BehaviorSubject.

    const subject = new Rx.Subject();
    const asyncSubject = new Rx.AsyncSubject();
    const behaviorSubject = new Rx.BehaviorSubject();
    
    console.log('before init - behaviorSubject', behaviorSubject.value)
    
    subject.next('INIT');
    asyncSubject.next('INIT');
    behaviorSubject.next('INIT');
    
    console.log('before subscribe - behaviorSubject', behaviorSubject.value)
    
    // Subscribe before
    subject.subscribe(x => console.log('before complete - subject', x))
    asyncSubject.subscribe(x => console.log('before complete - asyncSubject', x))
    behaviorSubject.subscribe(x => console.log('before complete - behaviorSubject', x))
    
    subject.next('NEXT');
    subject.complete();
    
    asyncSubject.next('NEXT');
    asyncSubject.complete();
    
    behaviorSubject.next('NEXT');
    behaviorSubject.complete();
    
    // Subscribe after
    subject.subscribe({
      next: x => console.log('after complete - subject', x),
      complete: () => console.log('after complete - subject COMPLETE')
    })
    asyncSubject.subscribe({
      next: x => console.log('after complete - asyncSubject', x),
      complete: () => console.log('after complete - asyncSubject COMPLETE')
    })
    behaviorSubject.subscribe({
      next: x => console.log('after complete - behaviorSubject', x),
      complete: () => console.log('after complete - behaviorSubject COMPLETE')
    })
    .as-console-wrapper { max-height: 100% ! important; top: 0 }

提交回复
热议问题