Gerald Hughes
Gerald Hughes

Reputation: 6159

'ObjectUnsubscribedError object unsubscribed' on valueChanges in custom validator over form

I have a custom validation service that I'm using in my form, in case one input depends on another

this.myForm = new FormGroup(group, [ServiceValidator.customValidator]);

The validator looks similar to this:

static customValidator(g: FormGroup) {
    this._unsubscriber$ = new Subject<boolean>();

    g.controls['myControl'].valueChanges.pipe(takeUntil(this._unsubscriber$)).subscribe(values => {
       // Logic here
        if (this._unsubscriber$) {
            this._unsubscriber$.next(true);
            this._unsubscriber$.unsubscribe();
        } 
    });
}

I noticed that if I change the value to myControl input several times, it starts to get slower and slower, although I tried to unsubscribe. When I started using takeUntil, I started to get this error.

My ServiceValidator is not a angular component, so I can't use ngOnDestroy. Also, the customValidator gets called whenever a value in the form gets changed.

What am I doing wrong? How do I safely unsubscribe?

Upvotes: 0

Views: 458

Answers (1)

Random
Random

Reputation: 3236

With a takeuntil, you should not use

this._unsubscriber$.next(true);
this._unsubscriber$.unsubscribe();

but

this._unsubscriber$.next(true);
this._unsubscriber$.complete();

Upvotes: 4

Related Questions