Search code examples
typescriptrxjsobservablesubscription

Wait for observable to give value to variable before trying to do something with it


I have a problem which that keeps popping up when dealing with observables:

someObservable$.subscribe(response => this.ref = response);

if (this.ref) {
    // do something with this.ref value
}
ERROR: this.ref is undefined

How do I wait until the subscription has provided this.ref with a value, before running code which relies on this.ref?

I'm assuming this has something to do with the time, like subscription to database needs a certain amount of time before read is complete, because if i attach the above code to a button click event, it will execute only after I click the button a few times. So I could, in theory, use setTimeout to wait 5 seconds, then run the code. But I was wondering if there is an RXJS operator or something else that's made to deal with this problem.

Thanks


Solution

  • Assuming someObservable$ is an observable for a HTTP request, move the code that relies on this.ref to be inside the subscription handler. Here's an example:

    someObservable$.subscribe(response => {
        this.ref = response;
        // Do whatever work relies on this.ref here.
    });
    

    The subscription handler is fired once you receive a response from the HTTP request. So that should be the time to do the work needed. If this.ref is a variable for a template, then the template should take care of updating the view with the new value automatically.