我们有一个功能,可观察到来自后端的流。但是,我们也希望能够将其推向可观察的位置,以便在后端完成更改之前先查看更改。为此,我尝试退回一个主题,但是取消订阅后,连接仍在继续。
换句话说,在下面的代码中,我们希望console.log(i)
在订阅主题之前不要开始,而在取消订阅主题时结束:
import { ReplaySubject, Observable, interval } from 'rxjs';
import { tap } from 'rxjs/operators'
function test() {
const obs = interval(1000).pipe(tap(i => console.log(i)));
const subj = new ReplaySubject(1);
obs.subscribe(subj);
return subj;
}
const subject = test();
subject.next('TEST');
const subscription = subject.pipe(
tap(i => console.log('from outside ' + i))
).subscribe()
setTimeout(_ => subscription.unsubscribe(), 5000);
答案 0 :(得分:2)
您不能在subscribe
中test
。我猜您想创建一个Observable和Subject,以及merge这些对象-您将必须分别返回它们。
return [subject, merge(subject, obs)]
然后
const [subject, obs] = test();
subject.next()
但是我会通过提供subject作为参数来做到这一点。
import { ReplaySubject, Observable, interval, merge } from 'rxjs';
import { tap } from 'rxjs/operators'
function test(subject) {
return merge(
interval(1000).pipe(tap(i => console.log(i))),
subject
);
}
const subject = new ReplaySubject(1);
const obs = test(subject);
subject.next('TEST');
const subscription = obs.pipe(
tap(i => console.log('from outside ' + i))
).subscribe()
setTimeout(_ => subscription.unsubscribe(), 5000);