summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/android/util/Topic.java
blob: eed13c9efcf77206712882803ceed527664b056f (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
86
87
88
89
90
91
92
93
94
95
96
97
/*
 * Copyright © 2017 John Wu <topjohnwu@gmail.com>
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

package com.wireguard.android.util;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Topic {

    private static final int NON_INIT = 0;
    private static final int PENDING = 1;
    private static final int PUBLISHED = 2;

    private int state = NON_INIT;
    private List<WeakReference<Subscriber>> subscribers;
    private Object[] results;

    public void subscribe(Subscriber sub) {
        if (subscribers == null) {
            subscribers = new LinkedList<>();
        }
        subscribers.add(new WeakReference<>(sub));
    }

    public void unsubscribe() {
        subscribers = null;
    }

    public void unsubscribe(Subscriber sub) {
        for (Iterator<WeakReference<Subscriber>> i = subscribers.iterator(); i.hasNext();) {
            WeakReference<Subscriber> subscriber = i.next();
            if (subscriber.get() == null || subscriber.get() == sub) {
                i.remove();
            }
        }
    }

    public void reset() {
        state = NON_INIT;
        results = null;
    }

    public boolean isPublished() {
        return state == PUBLISHED;
    }

    public void publish() {
        publish(true);
    }

    public void publish(boolean record, Object... results) {
        if (record)
            state = PUBLISHED;
        this.results = results;
        if (subscribers != null) {
            for (WeakReference<Subscriber> subscriber : subscribers) {
                if (subscriber.get() != null)
                    subscriber.get().onTopicPublished(this);
            }
        }
    }

    public Object[] getResults() {
        return results;
    }

    public boolean isPending() {
        return state == PENDING;
    }

    public void setPending() {
        state = PENDING;
    }

    public interface Subscriber {
        default void subscribeTopics() {
            for (Topic topic : getSubscription()) {
                if (topic.isPublished()) {
                    onTopicPublished(topic);
                }
                topic.subscribe(this);
            }
        }
        default void unsubscribeTopics() {
            for (Topic event : getSubscription()) {
                event.unsubscribe(this);
            }
        }
        void onTopicPublished(Topic topic);
        Topic[] getSubscription();
    }
}