Impure Pipe VS Event Subscription in Pipe

45 views Asked by At

I have a simple user requirement: to allow the user to select a time zone. Once the user selects a time zone, all the dates in the app should be transformed according to that time zone. It's important to note that there are many dates in the app.

For date transformation, I am using a custom Pipe. However, when the user changes their time zone, it gets updated in the service, but the pipe doesn't detect that change instantly. It takes some time to reflect the change. However, when I set my pipe to 'impure', it detects the change instantly. I know using impure pipe is not considered good so what should I do? Or is it suitable for the case? What about having an event subscription in the Pipe instead? Or any other best practice to tackle this?

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment-timezone';
import { AuthService } from '../services/auth.service'

@Pipe({
  name: 'displayDate',
  pure: false
})
export class DisplayDatePipe implements PipeTransform {
    constructor(private auth: AuthService) {
    }

    transform(value: any, format?: string): any {
        if (!value || !this.auth?.timezone) return ''

        return moment(value).tz(this.auth?.timezone).format(format ?? 'MMM D, YYYY') + ` (${this.auth.timezone})`
    }
}
0

There are 0 answers