Search code examples
angularngrx-store

Can I still rely on pipe(take(1)).subscribe() to run synchronously?


I'm trying to get the most recent state of an observable synchroniously. According to this migration document for ngrx/store 2.0 you can always rely on subscribe() running synchronously if you have to get the state value.

I can't find any current documentation that supports this. Does this still hold for current versions of the store (e.g. 7.4.0)?

Sample code:

method(someId: string): string {
    let value: string;
    this.service.getSomeValue$(someId).pipe(take(1)).subscribe(s => value = s);
    return value;
}

Solution

  • If you need to know if some code runs synchronous without diving deep into the source code, you can test it.

    Set some asynchronous code (like setTimeout or Promise (first runs on Macro queue, second on Micro queue)), then code you want to test and then some synchronous code. Result should be:

    • the code you test
    • synchronous code
    • asynchronous code

    If result is like that, you code is synchronous.