Altering combineLatest to emit the result without awaiting other observables - rxjs

I have this rxjs code where cobineLatest is used
cobineLatest(
this.controls.toArray().map(c => c.changeEvent.asObservable())
).subscribe(x => {
console.log(x);
});
The thing is that there won't be any result in subscription until all observables emits, I wonder how would you change that behavior so it will start emitting even if one single observable emits?

I suggest you to just pipe the single observables to start with null. This way you ensure that each observable has emitted at least one value:
cobineLatest(
this.controls.toArray().map(c => c.changeEvent.asObservable().pipe(startWith(null)))
).subscribe(x => {
console.log(x);
});

If your are interested in the emitted value only (not the array), then merge might be your friend.
merge(
this.controls.toArray().map(c => c.changeEvent.asObservable())
).subscribe(x => {
console.log(x); // x is not an array
});

Related

Repeat on an BehaviorSubject

I want to reemit the last value of my observable at a fix interval, to I tried
obs.pipe(repeat({delay:1000})).subscribe(x => console.log('Emitted', x));
but it did not work. after looking into this, my observable is in fact a BehaviorSubject.
So my Question is Why does the 1st emits every second
of('Observable').pipe(repeat({ delay: 1000 })).subscribe(x => console.log(x));
but not the this?
var bs = new BehaviorSubject('BehaviorSubject');
bs.pipe(repeat({ delay: 1000 })).subscribe(x => console.log(x));
How to do it with my BehaviorSubject?
Edit
And I would also like to reset my timer when the subject emits a new value.
the solution I found is
var bs = new BehaviorSubject('BehaviorSubject');
bs.pipe(switchMap(x => timer(0,1000).pipe(map => () => x)).subscribe(x => console.log(x));
but it feels ugly.
You can derive an observable from your BehaviorSubject that switchMaps to a timer that emits the received value. Whenever the subject emits, the timer is reset and will emit the latest value:
const bs = new BehaviorSubject('initial value');
const repeated = bs.pipe(
switchMap(val => timer(0, 1000).pipe(
map(() => val)
))
);
Here's a StackBlitz demo.
So my Question is Why does the 1st emits every second, but not the this?
The reason your example code using of as the source works and not the code using the BehaviorSubject can be found in the documentation of the repeat operator:
Returns an Observable that will resubscribe to the source stream when the source stream completes.
The observable created using of completes after it emits the provided value, so it will resubscribe. Since the BehaviorSubject was not completed, it will not resubscribe.

Chaining two dependent observables in rxjs

I have an observable that emits a series of messages, say obs1. Then a second observable, obs2, that needs some data from the last message emitted by obs1 and emits another series of messages. I would like to "chain" these 2 observables to produce an observable obs3 that serially emits ALL messages from obs1 and obs2.
The solution I came up with so far is:
obs3 = concat(
obs1,
obs1.pipe(
last(),
concatMap(lastMessage => obs2(lastMessage)),
);
But this has the flaw that obs1 is executed (subscribed to) 2 times.
Is there a more direct way to achieve this? Something like a concatMapWithSelf() operator that would work like this:
obs3 = obs1.pipe(
concatMapWithSelf(lastMessage => obs2(lastMessage)),
);
Thank you!
Sounds like you could use ConnectableObservable. In RxJS 7 I believe it would be even easier and better readable with multicast() but that's going to be deprecated in RxJS 8 so the only option is probably wrapping the source Observable with connectable() and then manually calling connect().
const obs1 = connectable(
defer(() => {
console.log('new subscription');
return of('v1', 'v2', 'v3', 'v4');
})
);
const obs2 = msg => of(msg);
const obs3 = merge(
obs1,
obs1.pipe(
last(),
concatMap(lastMessage => obs2(lastMessage))
)
);
obs3.subscribe(console.log);
obs1.connect();
Live demo: https://stackblitz.com/edit/rxjs-2uheg4?devtoolsheight=60
If obs1 is always asynchronous then probably you could use share() but that would behave differently with synchronous sources so using ConnectableObservable should be more safe.

How do I create an observable which emits a value from an ngrx selector, then another value after a delay?

Given an ngrx selector:
store.select('count')
I want to create an observable that will emit values emitted by the selector, then emit another specific value after a delay.
Using concat doesn't work as (I assume) the selector doesn't complete, so the 0 is never emitted:
this.count$ = concat(store.select('count'), of(0).pipe(delay(2000)));
Stackblitz: https://stackblitz.com/edit/so-selector-delay?file=src/app/my-counter/my-counter.component.ts
- click 'Increment' button - Current Count should change to 1 then back to 0 after 2 seconds.
If you want to emit the store.select('count') value, then essentially reset it to 0 after not receiving an emission for 2 seconds, you can use a switchMap to create a source that emits two values:
The emitted count
The "default" value of 0 after 2000ms
The trick here is that the second value (0) will NOT be emitted if another store.select('count') value is received, because switchMap will create a new source and "switch" to that:
this.count$ = store.select('count').pipe(
switchMap(count => concat(
of(count),
of(0).pipe(delay(2000))
))
);
Here's a working StackBlitz demo.
It might even be worth creating a custom operator:
this.count$ = this.store.select('count').pipe(
resetAfterDelay(0, 2000)
);
export function resetAfterDelay<T>(defaultValue: T, delayMs: number) {
return switchMap((value: T) => concat(
of(value),
of(defaultValue).pipe(delay(delayMs))
));
}
StackBlitz
Below is an approach using combineLatest and BehaviorSubject
We are hold a value in a subject and create a timer that emits value 0 after 2s. So we have two Observables, one emits immediately and the other after 2s. We combine this two and the effect is a single observable as desired
valueHolderSubject$ = new BehaviorSubject(0);
...
this.count$ = combineLatest([
store.select("count").pipe(
tap(x => this.valueHolderSubject$.next(x)),
tap(() =>
timer(2000).subscribe({
next: () => {
this.valueHolderSubject$.next(0);
}
})
),
map(() => this.valueHolderSubject$.value),
distinctUntilChanged()
),
this.valueHolderSubject$
]).pipe(map(([, x]) => x));
Demo Here
A per my comments on the answer from BizzyBob, I was getting unreliable results. But I refined it to work using:
this.count$ = merge(
store.select('count'),
store.select('count').pipe(delay(2000), map(_ => 0))
);
See stackblitz: https://stackblitz.com/edit/so-selector-delay-merge-working?file=src/app/my-counter/my-counter.component.ts

Replace Observable which already has subscribers with other Observable

I have an Observable which gets later gets "replace" with another Observable.
How can I swap the Observable without loosing my subscribers?
const source = NEVER
const source2 = interval(1000);
source.subscribe(x => console.log(x));
// source.switch(source2)
source.switch(source2) is obviously not a valid operation. But it demonstrates, what I'dlike to achieve.
Same example on StackBlitz:
https://stackblitz.com/edit/rxjs-76a7ew
What would I need to do after the subscribtion, so this code will start printing the numbers from interval?
so you want switch to source2
source.pipe(
switchMap(() => source2)
).subscribe(x => console.log(x)); // x here is source2
you could use mergeMap or concatMap as well but I would recommend to use switchMap in this case as it's going to cancel the previous emit

RxJS - reusing an observable which has completed

Link to code in stackblitz
Is there a way to repeat a completed observable multiple times?
Say I have a button that on click creates an interval observable that emits 10 values, then completes:
fromEvent(button, 'click').pipe(
switchMapTo(interval(500)),
takeWhile(i => i < 10)
)
In the subscription I want to handle both the next and the complete methods:
.subscribe(
i => console.log(i),
() => {},
() => console.log('completed')
);
In this way - the first click will emit one sequence and once it completes, subsequent clicks will not emit again. Is there any way to write this so that all clicks emit the sequence?
I think you should complete the inner observable and not the whole sequence.
(takeWhile should be piped to interval);
You should use switchMap only if you are happy to dismiss the old sequence once a new click event comes in. mergeMap or concatMap otherwise.
const sequence = () => interval(500).pipe(take(10));
fromEvent(button, 'click').pipe(
switchMap(sequence),
)

Resources