setTimeout()中的主题不起作用

时间:2019-01-30 09:49:40

标签: javascript observable settimeout subject

我正在尝试RxJS的主题。在下面的2个代码段中,输出是不同的。我不明白为什么'setTimeout'方法内的'subscribe'不会记录该值。有人可以帮我解决这个问题吗?谢谢。

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

const subject = new Subject();

subject.subscribe((value) => console.log(value)); 

setTimeout(() => {
  subject.subscribe((value) => console.log(value)); 
}, 2000);

const observable = new Observable((observer) => {
  console.log('called only once')
  observer.next(Math.random())
});  

observable.subscribe(subject); 

Output: 

called only once
0.253655945545456

================================================ ==

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

const subject = new Subject();

subject.subscribe((value) => console.log(value)); 
subject.subscribe((value) => console.log(value)); 

const observable = new Observable((observer) => {
  console.log('called only once')
  observer.next(Math.random())
});  

observable.subscribe(subject); 

Output: 

called only once
0.253655945545456
0.253655945545456

0 个答案:

没有答案