如何将这种冷观测变成热?

时间:2019-08-09 09:01:24

标签: rxjs observable

我似乎无法将这种冷的观测转变为高温:

const test = new BehaviorSubject('test').pipe(tap(() => console.log('I want this to be logged only once to the console!')))

const grr = test.pipe(
  share(), // share() seems to not do anything
  take(1), // The culprit is here, causes logging to take place 5 times (5 subscribers)
  share() // share() seems to not do anything
)

grr.subscribe(() => console.log(1))
grr.subscribe(() => console.log(2))
grr.subscribe(() => console.log(3))
grr.subscribe(() => console.log(4))
grr.subscribe(() => console.log(5))

// Expected output:
// 'I want this to be logged only once to the console!'
// 1
// 2
// 3
// 4
// 5

我应该如何改变它以产生所需的输出?

1 个答案:

答案 0 :(得分:2)

您可以像这样使用publishReplayrefCount运算符:

import { interval, BehaviorSubject } from 'rxjs';
import { publishReplay, tap, refCount } from 'rxjs/operators';

const test = new BehaviorSubject('test').
                  pipe(
                    tap(() => console.log('I want this to be logged only once to the console!')
                    ),
                    publishReplay(1),
                    refCount()
                  );

test.subscribe(() => console.log(1));
test.subscribe(() => console.log(2));
test.subscribe(() => console.log(3));
test.subscribe(() => console.log(4));

正在工作的Stackblitz:https://stackblitz.com/edit/typescript-cvcmq6?file=index.ts