Skip to content

Commit 6636e1c

Browse files
authored
Merge pull request #17 from vibe-d/value_modify
Add Value.modify() shorthand syntax for modifying parts of a Value!T
2 parents 491b706 + 6a3a14c commit 6636e1c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

source/observable/value.d

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,36 @@ static assert (isObservable!(typeof(Value!int.init.mapValue!(i => "foo"))));
133133
static assert (isReactiveValue!(typeof(Value!int.init.mapValue!(i => "foo"))));
134134

135135

136+
/** Modify the value using a callback.
137+
138+
This is a shorthand for getting the current value, modifying it and
139+
setting the modified value.
140+
*/
141+
void modify(alias MODIFIER, T)(ref Value!T value)
142+
{
143+
auto val = value.get;
144+
MODIFIER(val);
145+
value.set(val);
146+
}
147+
148+
///
149+
unittest {
150+
struct S {
151+
int width;
152+
int height;
153+
}
154+
155+
Value!S value;
156+
157+
// set the whole value
158+
value = S(1, 2);
159+
160+
// modify just one field
161+
value.modify!((ref s) { s.height += 10; });
162+
assert(value == S(1, 12));
163+
}
164+
165+
136166
/** Determines whether the given type implements the reactive value interface.
137167
*/
138168
enum isReactiveValue(V) = isObservable!V && is(typeof(V.init.get));

0 commit comments

Comments
 (0)