/
SpValueHolder.class.st
102 lines (83 loc) · 2.21 KB
/
SpValueHolder.class.st
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"
I am a class holding any object inside its unique instance variable.
Each time the instance variable value changes, an announcement is emitted.
The instance variable is accessed through `value` and `value:` while the registration is done by `whenChangedDo: aBlock`.
In addition, infinite loops of propagation are prevented.
Use case: you have two lists A, and B, and you want to keep their selection synchronised.
So when A selection changes, you set B selection.
But since B selection changes, you set A selection, and so on…
This case is prevented by the use of a `lock` variable.
"
Class {
#name : #SpValueHolder,
#superclass : #Object,
#instVars : [
'subscriptions',
'lock',
'value'
],
#category : #'Spec2-Core-Observable'
}
{ #category : #'instance creation' }
SpValueHolder class >> value: contents [
^ self new
rawValue: contents;
yourself
]
{ #category : #initialization }
SpValueHolder >> initialize [
super initialize.
lock := false.
subscriptions := OrderedCollection new
]
{ #category : #printing }
SpValueHolder >> printOn: aStream [
super printOn: aStream.
aStream
nextPutAll: '[ ';
print: self value;
nextPutAll: ' ]'
]
{ #category : #accessing }
SpValueHolder >> rawValue: aValue [
value := aValue
]
{ #category : #accessing }
SpValueHolder >> subscriptions [
^ subscriptions
]
{ #category : #accessing }
SpValueHolder >> subscriptions: anObject [
subscriptions := anObject
]
{ #category : #transfert }
SpValueHolder >> transferSubscriptionsTo: aSpValueHolder [
aSpValueHolder subscriptions: subscriptions
]
{ #category : #evaluating }
SpValueHolder >> value [
^ value
]
{ #category : #accessing }
SpValueHolder >> value: anObject [
"Handle circular references as explained in the class comment"
lock ifTrue: [ ^ self ].
lock := true.
[ | oldValue |
oldValue := value.
value := anObject.
self valueChanged: oldValue ]
ensure: [ lock := false ]
]
{ #category : #accessing }
SpValueHolder >> valueChanged [
self valueChanged: nil
]
{ #category : #accessing }
SpValueHolder >> valueChanged: oldValue [
subscriptions do: [ :block | block cull: self value cull: oldValue ]
]
{ #category : #enumerating }
SpValueHolder >> whenChangedDo: aBlock [
subscriptions add: aBlock
]