-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
81 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
website/src/content/docs/guides/bi-directional-data-flow.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
--- | ||
title: Bi-directional Data Flow | ||
description: By default, Signals are uni-directional but can be used in a bi-directional way if needed. | ||
--- | ||
|
||
By default, Signals are uni-directional but can be used in a bi-directional way if needed. | ||
|
||
> Warning: Bi-directional data flow should only be used when necessary as it can lead to infinite loops if not used correctly. | ||
Consider the following example: | ||
|
||
```dart | ||
final a = signal(0); | ||
final b = signal(0); | ||
effect(() { | ||
b.value = a.value + 1; | ||
}); | ||
effect(() { | ||
a.value = b.value + 1; | ||
}); | ||
``` | ||
|
||
In this example, `a` and `b` are two signals that are dependent on each other. When `a` changes, `b` should update, and when `b` changes, `a` should update. | ||
|
||
This however can lead to an infinite loop and will throw a `EffectCycleDetectionError`. To prevent this, you can use the `untracked` method to prevent the signal from updating itself. | ||
|
||
```dart | ||
final a = signal(0); | ||
final b = signal(0); | ||
effect(() { | ||
b.value = untracked(() => a.value + 1); | ||
}); | ||
effect(() { | ||
a.value = untracked(() => b.value + 1); | ||
}); | ||
``` | ||
|
||
This will prevent the infinite loop and allow the signals to update each other without causing an error. | ||
|
||
Signals are synchronous and will update immediately when the value is set. This means that the value will be updated before the next effect is run. This allows you to create bi-directional data flow in a predictable way. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters