OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library observe.src.observable; | |
6 | |
7 import 'dart:async'; | |
8 import 'dart:collection'; | |
9 | |
10 import 'package:smoke/smoke.dart' as smoke; | |
11 import 'package:observe/observe.dart'; | |
12 | |
13 // Note: this is an internal library so we can import it from tests. | |
14 // TODO(jmesserly): ideally we could import this with a prefix, but it caused | |
15 // strange problems on the VM when I tested out the dirty-checking example | |
16 // above. | |
17 import 'dirty_check.dart'; | |
18 | |
19 /// Represents an object with observable properties. This is used by data in | |
20 /// model-view architectures to notify interested parties of [changes] to the | |
21 /// object's properties (fields or getter/setter pairs). | |
22 /// | |
23 /// The interface does not require any specific technique to implement | |
24 /// observability. You can implement it in the following ways: | |
25 /// | |
26 /// - extend or mixin this class, and let the application call [dirtyCheck] | |
27 /// periodically to check for changes to your object. | |
28 /// - extend or mixin [ChangeNotifier], and implement change notifications | |
29 /// manually by calling [notifyPropertyChange] from your setters. | |
30 /// - implement this interface and provide your own implementation. | |
31 abstract class Observable { | |
32 /// Performs dirty checking of objects that inherit from [Observable]. | |
33 /// This scans all observed objects using mirrors and determines if any fields | |
34 /// have changed. If they have, it delivers the changes for the object. | |
35 static void dirtyCheck() => dirtyCheckObservables(); | |
36 | |
37 StreamController _changes; | |
38 | |
39 Map<Symbol, Object> _values; | |
40 List<ChangeRecord> _records; | |
41 | |
42 /// The stream of change records to this object. Records will be delivered | |
43 /// asynchronously. | |
44 /// | |
45 /// [deliverChanges] can be called to force synchronous delivery. | |
46 Stream<List<ChangeRecord>> get changes { | |
47 if (_changes == null) { | |
48 _changes = new StreamController.broadcast(sync: true, | |
49 onListen: _observed, onCancel: _unobserved); | |
50 } | |
51 return _changes.stream; | |
52 } | |
53 | |
54 /// True if this object has any observers, and should call | |
55 /// [notifyChange] for changes. | |
56 bool get hasObservers => _changes != null && _changes.hasListener; | |
57 | |
58 void _observed() { | |
59 // Register this object for dirty checking purposes. | |
60 registerObservable(this); | |
61 | |
62 var values = new Map<Symbol, Object>(); | |
63 | |
64 // Note: we scan for @observable regardless of whether the base type | |
65 // actually includes this mixin. While perhaps too inclusive, it lets us | |
66 // avoid complex logic that walks "with" and "implements" clauses. | |
67 var queryOptions = new smoke.QueryOptions(includeInherited: true, | |
68 includeProperties: false, withAnnotations: const [ObservableProperty]); | |
69 for (var decl in smoke.query(this.runtimeType, queryOptions)) { | |
70 var name = decl.name; | |
71 // Note: since this is a field, getting the value shouldn't execute | |
72 // user code, so we don't need to worry about errors. | |
73 values[name] = smoke.read(this, name); | |
74 } | |
75 | |
76 _values = values; | |
77 } | |
78 | |
79 /// Release data associated with observation. | |
80 void _unobserved() { | |
81 // Note: we don't need to explicitly unregister from the dirty check list. | |
82 // This will happen automatically at the next call to dirtyCheck. | |
83 if (_values != null) { | |
84 _values = null; | |
85 } | |
86 } | |
87 | |
88 /// Synchronously deliver pending [changes]. Returns true if any records were | |
89 /// delivered, otherwise false. | |
90 // TODO(jmesserly): this is a bit different from the ES Harmony version, which | |
91 // allows delivery of changes to a particular observer: | |
92 // http://wiki.ecmascript.org/doku.php?id=harmony:observe#object.deliverchange
records | |
93 // | |
94 // The rationale for that, and for async delivery in general, is the principal | |
95 // that you shouldn't run code (observers) when it doesn't expect to be run. | |
96 // If you do that, you risk violating invariants that the code assumes. | |
97 // | |
98 // For this reason, we need to match the ES Harmony version. The way we can do | |
99 // this in Dart is to add a method on StreamSubscription (possibly by | |
100 // subclassing Stream* types) that immediately delivers records for only | |
101 // that subscription. Alternatively, we could consider using something other | |
102 // than Stream to deliver the multicast change records, and provide an | |
103 // Observable->Stream adapter. | |
104 // | |
105 // Also: we should be delivering changes to the observer (subscription) based | |
106 // on the birth order of the observer. This is for compatibility with ES | |
107 // Harmony as well as predictability for app developers. | |
108 bool deliverChanges() { | |
109 if (_values == null || !hasObservers) return false; | |
110 | |
111 // Start with manually notified records (computed properties, etc), | |
112 // then scan all fields for additional changes. | |
113 List records = _records; | |
114 _records = null; | |
115 | |
116 _values.forEach((name, oldValue) { | |
117 var newValue = smoke.read(this, name); | |
118 if (oldValue != newValue) { | |
119 if (records == null) records = []; | |
120 records.add(new PropertyChangeRecord(this, name, oldValue, newValue)); | |
121 _values[name] = newValue; | |
122 } | |
123 }); | |
124 | |
125 if (records == null) return false; | |
126 | |
127 _changes.add(new UnmodifiableListView<ChangeRecord>(records)); | |
128 return true; | |
129 } | |
130 | |
131 /// Notify that the field [name] of this object has been changed. | |
132 /// | |
133 /// The [oldValue] and [newValue] are also recorded. If the two values are | |
134 /// equal, no change will be recorded. | |
135 /// | |
136 /// For convenience this returns [newValue]. | |
137 notifyPropertyChange(Symbol field, Object oldValue, Object newValue) | |
138 => notifyPropertyChangeHelper(this, field, oldValue, newValue); | |
139 | |
140 /// Notify observers of a change. | |
141 /// | |
142 /// For most objects [Observable.notifyPropertyChange] is more convenient, but | |
143 /// collections sometimes deliver other types of changes such as a | |
144 /// [ListChangeRecord]. | |
145 /// | |
146 /// Notes: | |
147 /// - This is *not* required for fields if you mixin or extend [Observable], | |
148 /// but you can use it for computed properties. | |
149 /// - Unlike [ChangeNotifier] this will not schedule [deliverChanges]; use | |
150 /// [Observable.dirtyCheck] instead. | |
151 void notifyChange(ChangeRecord record) { | |
152 if (!hasObservers) return; | |
153 | |
154 if (_records == null) _records = []; | |
155 _records.add(record); | |
156 } | |
157 } | |
158 | |
159 // TODO(jmesserly): remove the instance method and make this top-level method | |
160 // public instead? | |
161 // NOTE: this is not exported publically. | |
162 notifyPropertyChangeHelper(Observable obj, Symbol field, Object oldValue, | |
163 Object newValue) { | |
164 | |
165 if (obj.hasObservers && oldValue != newValue) { | |
166 obj.notifyChange(new PropertyChangeRecord(obj, field, oldValue, newValue)); | |
167 } | |
168 return newValue; | |
169 } | |
OLD | NEW |