Search code examples
reduxrxjsngrx

Delay emitted observable values depending on the value of another observable


I am using forkJoin to wait for the completion of 4 observables. With the last emitted values from each, I use switchMap to trigger some NgRx actions (ConfiguratorLoaded, GetProjectMembers, SwitchOrganization):

forkJoin(
    this.projectsService.getProject(action.projectId),
    this.flavors$,
    this.images$,
    this.storageDefinitions$
).pipe(
    switchMap(([project, flavors, images, storageDefinitions]) => [
        new ConfiguratorLoaded(
            flavors,
            images,
            storageDefinitions,
            project
        ),
        new GetProjectMembers(action.projectId),
        new SwitchOrganization(
            this.getOrganizationById(project.organizationId)
        ),
    ])
);

I have another observable loaded$ which is of type Observable<boolean>and not in the code example above. How can I get the 3 NgRx actions to be triggered when loaded$ has the value true and not before? As long as loaded$ has the value false, the actions should not be triggered. So it's kind of a pause.


Solution

  • If I understand correctly, you should be able to do this:

    combineLatest([
        this.loaded$,
        this.projectsService.getProject(action.projectId),
        this.flavors$,
        this.images$,
        this.storageDefinitions$
    ]).pipe(
       filter(([loaded]) => Boolean(loaded)),
       // ...
    )
    

    The combineLatest will re-emit each time the this.loaded$ stream emits.

    If this.loaded$ emits false, the filter will skip processing the switchMap.

    If this.loaded$ emits true, the filter will continue and process the switchMap.

    This then effectively "waits" until this.loaded$ is true before it executes your NgRx actions.