Skip to content

Commit 9f5197a

Browse files
SkyZeroZxmmalerba
authored andcommitted
docs: add equal option to toSignal for custom value comparison (angular#64241)
PR Close angular#64241
1 parent fd8383a commit 9f5197a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

adev/src/content/ecosystem/rxjs-interop/signals-interop.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,31 @@ By default, `toSignal` automatically unsubscribes from the Observable when the c
5555

5656
To override this behavior, you can pass the `manualCleanup` option. You can use this setting for Observables that complete themselves naturally.
5757

58+
#### Custom equality comparison
59+
60+
Some observables may emit values that are **equals** even though they differ by reference or minor detail. The `equal` option lets you define a **custom equal function** to determine when two consecutive values should be considered the same.
61+
62+
When two emitted values are considered equal, the resulting signal **does not update**. This prevents redundant computations, DOM updates, or effects from re-running unnecessarily.
63+
64+
```ts
65+
import { Component } from '@angular/core';
66+
import { toSignal } from '@angular/core/rxjs-interop';
67+
import { interval, map } from 'rxjs';
68+
69+
@Component(/* ... */)
70+
export class EqualExample {
71+
temperature$ = interval(1000).pipe(
72+
map(() => ({ temperature: Math.floor(Math.random() * 3) + 20 }) ) // 20, 21, or 22 randomly
73+
);
74+
75+
// Only update if the temperature changes
76+
temperature = toSignal(this.temperature$, {
77+
initialValue: { temperature : 20 },
78+
equal: (prev, curr) => prev.temperature === curr.temperature
79+
});
80+
}
81+
```
82+
5883
### Error and Completion
5984

6085
If an Observable used in `toSignal` produces an error, that error is thrown when the signal is read.

0 commit comments

Comments
 (0)