summaryrefslogtreecommitdiffstats
blob: cfa8665e9aefa3999a3973b13a25b90b30b1c386 (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
/*
 * Copyright (c) 2010, Isode Limited, London, England.
 * All rights reserved.
 */
package com.isode.stroke.signals;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * An approximation of the boost::signals system, although a little more warty.
 */
public class Signal {

    private final Map<SignalConnection, Slot> binds_ = Collections.synchronizedMap(new HashMap<SignalConnection, Slot>());

    public SignalConnection connect(Slot bind) {
        final SignalConnection connection = new SignalConnection();
        binds_.put(connection, bind);
        connection.onDestroyed.connectWithoutReturn(new Slot() {

            public void call() {
                binds_.remove(connection);
            }
        });
        return connection;
    }

    public SignalConnection connect(final Signal target) {
        return connect(new Slot() {
            public void call() {
                target.emit();
            }
        });
    }

    void connectWithoutReturn(Slot bind) {
        binds_.put(null, bind);
    }

    public void emit() {
        ArrayList<Slot> binds = new ArrayList<Slot>();
        binds.addAll(binds_.values());
        for (Slot bind : binds) {
            bind.call();
        }
    }

    public void disconnectAll() {
        binds_.clear();
    }
}