angularrxjsobservableangular-router-events

rxjs and angular router events: Set boolean to inital value after first emit


this function below should return true if an angular router event was triggered.

private routeChanged$(): Observable<boolean> {
    return this.router.events.pipe(
        filter(event => event instanceof NavigationEnd),
        mapTo(true),
        startWith(false),
        untilDestroyed(this)
    );
}

it works fine but it should also reset again the inital value (false) after the event was fired so i basically want to set the boolean back to false after it emits true the first time (when the route changed) (sorry for my bad english, i hope you get my point)


Solution

  • Do you mean it should immediately emit false again after true?

    In that case you could do:

    private routeChanged$(): Observable<boolean> {
        return this.router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            switchMapTo([true, false]),
            startWith(false),
            untilDestroyed(this)
        );
    }
    

    switchMapTo will "subscribe" to the array - which is interpreted as an Observable emitting two values, true and false.