Given two sources, one of which might be undefined how can I combineLatest of the two?
const observable1 = interval(100);
const observable2 = this.ref?.observable; // this is a reference to an angular viewchild that will not exist until some unknown point in the future
combineLatest([observable1, observable2]).subscribe(...)
I need the output observable that I’m subscribing to subscribe to this.ref.observable as soon as this.ref is defined (but I don’t know when that will be).
What I tried…
observable1.pipe(
startWith(of(true)),
switchMap((_) => interval(10)),
skipWhile((_) => !this.ref),
switchMap((_) => observable1),
combineLatestWith(this.ref?.observable ?? EMPTY),
)
.subscribe((val1, val2]) => {...})
But a) I couldn’t figure out what the TS errors I was getting around the types returned from the combineLatestWith and b) that seems overly complicated for what seems like a simple issue!
Is there a simpler way of getting emissions from a source observable if the object the source observable is on may be undefined at the time I want to start observing?
2
Answers
Create an BehaviorSubject that initially has
null
Then on
ngOnInit
orconstructor
subscribe for the changes!The view child generally becomes visible on
ngAfterViewInit
.My Solution for your Problem