DEV Community

Discussion on: What's the RxJs/ NgRx code bit that you are most proud of? (Round 2)

Collapse
 
johannesjo profile image
Johannes Millan • Edited

I start of with a (probably not impressive and in a 1000 ways improvable) simple timer used to hide an popup after a short while. The timer gets reset, if the popup is triggered again.

export class PopupComponent {
    private _triggerPopup$ = new Subject<any>();

    isShowPopup$: Observable<boolean> = this._triggerPopup$.pipe(
        switchMap((): Observable<boolean> => merge(
            of(true),
            timer(POPUP_TIMEOUT_DURATION).pipe(mapTo(false))
        )),
    );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
negue profile image
negue

How about?

export class PopupComponent {
    private _triggerPopup$ = new Subject<any>();

    // typing aren't needed since TypeScript will get the type by parsing the code
    isShowPopup$ = this._triggerPopup$.pipe(   
        switchMap(() => 
            timer(POPUP_TIMEOUT_DURATION).pipe(
               mapTo(false),
               startWith(true) // until the timer fires, you'll have this value
            )
        ),
    );
}

I don't know if this could be optimized further 😅

Collapse
 
johannesjo profile image
Johannes Millan

I've to admit that's prettier than mine! :)

Collapse
 
johannesjo profile image
Johannes Millan

It's a shame that this article didn't get more attention. I catch myself coming back to this particular comment time and time again :D