What you understand as 'remembering history' are just active subscriptions.
obs1.pipe(mergeMap(v => obs2))
maps each value from the source (obs1
) to a stream (obs2
). So you end up with multiple obs2
streams having an active subscription at the same time. These obs2
streams are merged in one output stream and run until they complete, error or you unsubscribe.
In your case obs2 = b2s
is a Subject which is a hot observable that doesn't terminate on its own. The final observables behaves like this:
this.b1s.pipe(
mergeMap(z1 => this.b2s.pipe(
map(z2 => `${z1} / ${z2}`)
))
).subscribe(z => console.log(z));
b1s: --0--1--2--3--4-------5--6--7--------
b2s-7: │ │ │ │ │ │ │ └--7/1---
b2s-6: │ │ │ │ │ │ └-----6/1---
b2s-5: │ │ │ │ │ └--------5/1---
b2s-4: │ │ │ │ └--4/0-----------4/1---
b2s-3: │ │ │ └-----3/0-----------3/1---
b2s-2: │ │ └--------2/0-----------2/1---
b2s-1: │ └-----------1/0-----------1/1---
b2s-0: └--------------0/0-----------0/1---
output: -----------------0/0-----------0/1---
1/0 1/1
2/0 2/1
3/0 3/1
4/0 4/1
5/1
6/1
7/1
The subscriptions to b2s-0
- b2s-4
are still active when b2s
emits 1
.
If you don't want the inner streams to run indefinitely you have to terminate them somehow. You could use take(1)
if you only want them to emit one value.
this.b1s.pipe(
mergeMap(z1 => this.b2s.pipe(
take(1), // <-- only emit 1 value and then complete
map(z2 => `${z1} / ${z2}`)
))
).subscribe(z => console.log(z));
b1s: --0--1--2--3--4-------5--6--7--------
b2s-7: │ │ │ │ │ │ │ └--7/1|
b2s-6: │ │ │ │ │ │ └-----6/1|
b2s-5: │ │ │ │ │ └--------5/1|
b2s-4: │ │ │ │ └--4/0|
b2s-3: │ │ │ └-----3/0|
b2s-2: │ │ └--------2/0|
b2s-1: │ └-----------1/0|
b2s-0: └--------------0/0|
output: -----------------0/0-----------5/1---
1/0 6/1
2/0 7/1
3/0
4/0
In the documentation obs2 = 10----10----10-|
is a cold observable that terminates after 3 emissions. It also generates the same 3 emissions for every subscriber (unlike your Subject).
ob1: --1-----------------------------3--------------5----------------------------|
obs2-3: │ │ └10*5------10*5------10*5-|
obs2-2: │ └10*3------10*3------10*3-|
obs2-1: └10*1------10*1------10*1-|
output: ---10*1------10*1------10*1------10*3------10*3-10*5-10*3-10*5------10*5----|
= --- 10 ------ 10 ------ 10 ------ 30 ------ 30 - 50 - 30 - 50 ------ 50 ----|
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…