'Read data from ngrx store directly

I saw in our codebase a lot of places using this pattern

getUrl() : string {
    let url = ''
    this.store.pipe(selectorConfig, take(1)).subscribe((config) => {
        url = config.url
    });
    return url;
}

Just want to check if this is async? will the selectorConfig emit only when config changes so this is an async call? There are also someone saying ngrx store is a behaviourObject so the moment you subscribe, it emits last value so this effectively is a sync function.

Could anyone confirm which is correct?



Solution 1:[1]

Unless you make it asynchronous it's a synchronous operation. As is the Subject.next method.

// Synchronous
getUrl() : string {
  let url = ''
  console.log('START');
  // considering that selectorConfig does not contain anything `asynchronous`, which it should not
  this.store.pipe(selectorConfig, take(1)).subscribe((config) => {
    url = config.url
    console.log('URL:', config.url);
  });
  console.log('START');
  return url;
}
/* OUTPUT
START
URL: <yourUrl>
END
*/

// Asynchronous
import { delay } from 'rxjs/operators';

getUrl() : string {
  let url = ''
  console.log('START');
  // adding a delay operator makes it asynchronous
  this.store.pipe(selectorConfig, delay(0), take(1)).subscribe((config) => {
    url = config.url
    console.log('URL:', config.url);
  });
  console.log('START');
  return url;
}
/* OUTPUT
START
END
URL: <yourUrl>
*/

There's a nice explanation to your question here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mat.hudak