首页 > 解决方案 > 如何将这种冷的可观察到的变成热的?

问题描述

我似乎无法将这个冷的可观察到的变成热的:

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

我应该如何改变它以产生想要的输出?

标签: rxjsobservable

解决方案


您可以像这样使用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


推荐阅读