1

I have two Observables in a container called settings and settingsLoading. I have an API call that retrieves some settings, and once that call completes, settingsLoading will be set to true and settings will contain the data from the API. I am passing the settings data to a component and passing settingsLoading to the same component as an Observable.

In that component, as seen below, I am subscribing to the settingsLoading Observable, and once loading is false, I make a couple of console logs so I can look at the settings data that should now be set. The console log always returns null unless I wrap it in a timeout of 0 seconds. Why do I need to do this? Is this a reliable way of handling this? Is there a better way to do this so I can avoid the timeout?

In the code below, the first console log will always return null and the second seems to always have the data I'm expecting:

subscribeToLoadSettings() {
    this.settingsLoading.subscribe(loading => {
        if (!loading) {
            // This doesn't work
            console.log('settings', this.settings);
            setTimeout(() => {
                // This works
                console.log('settings', this.settings);
            }, 0);
        }
    });
}
Bryan
  • 2,951
  • 11
  • 59
  • 101
  • can you include your code that loads the settings as well as how `settingsLoading` is updated. then we can help you structure it properly. – delashum Apr 05 '19 at 04:33

2 Answers2

-1

When one observable is depend on the result of other observable then you can use RxJS operator such as switchMap.

Zoha Irshad
  • 427
  • 5
  • 5
-1

If you do a subscribe into another subscribe, that will work fine, without timeout !!!

But for refactor code, you can use mergeMap or switchMap.

See code in: How to refactor a subscribe inside a subscribe in rxjs

Regards!

tavOu
  • 7
  • 1