aboutsummaryrefslogtreecommitdiff
path: root/libphobos/testsuite/libphobos.phobos/std_signals.d
blob: 255dbde7d754b3cab5c211871b9f7f0874e3920a (plain)
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
@system unittest
{
    import std.signals;

    import std.signals;

    int observedMessageCounter = 0;

    class Observer
    {   // our slot
        void watch(string msg, int value)
        {
            switch (observedMessageCounter++)
            {
                case 0:
                    assert(msg == "setting new value");
                    assert(value == 4);
                    break;
                case 1:
                    assert(msg == "setting new value");
                    assert(value == 6);
                    break;
                default:
                    assert(0, "Unknown observation");
            }
        }
    }

    class Observer2
    {   // our slot
        void watch(string msg, int value)
        {
        }
    }

    class Foo
    {
        int value() { return _value; }

        int value(int v)
        {
            if (v != _value)
            {   _value = v;
                // call all the connected slots with the two parameters
                emit("setting new value", v);
            }
            return v;
        }

        // Mix in all the code we need to make Foo into a signal
        mixin Signal!(string, int);

      private :
        int _value;
    }

    Foo a = new Foo;
    Observer o = new Observer;
    auto o2 = new Observer2;
    auto o3 = new Observer2;
    auto o4 = new Observer2;
    auto o5 = new Observer2;

    a.value = 3;                // should not call o.watch()
    a.connect(&o.watch);        // o.watch is the slot
    a.connect(&o2.watch);
    a.connect(&o3.watch);
    a.connect(&o4.watch);
    a.connect(&o5.watch);
    a.value = 4;                // should call o.watch()
    a.disconnect(&o.watch);     // o.watch is no longer a slot
    a.disconnect(&o3.watch);
    a.disconnect(&o5.watch);
    a.disconnect(&o4.watch);
    a.disconnect(&o2.watch);
    a.value = 5;                // so should not call o.watch()
    a.connect(&o2.watch);
    a.connect(&o.watch);        // connect again
    a.value = 6;                // should call o.watch()
    destroy(o);                 // destroying o should automatically disconnect it
    a.value = 7;                // should not call o.watch()

    assert(observedMessageCounter == 2);
}