Topic: make reentrant

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2018-06-01 17:34:59 +02:00
parent 3d57eb633e
commit 65292aaa79

View File

@ -24,14 +24,17 @@ public class Topic {
if (subscribers == null) {
subscribers = new LinkedList<>();
}
synchronized (subscribers) {
subscribers.add(new WeakReference<>(sub));
}
}
public void unsubscribe() {
subscribers = null;
}
public void unsubscribe(Subscriber sub) {
synchronized (subscribers) {
for (Iterator<WeakReference<Subscriber>> i = subscribers.iterator(); i.hasNext(); ) {
WeakReference<Subscriber> subscriber = i.next();
if (subscriber.get() == null || subscriber.get() == sub) {
@ -39,6 +42,7 @@ public class Topic {
}
}
}
}
public void reset() {
state = NON_INIT;
@ -58,7 +62,11 @@ public class Topic {
state = PUBLISHED;
this.results = results;
if (subscribers != null) {
for (WeakReference<Subscriber> subscriber : subscribers) {
List<WeakReference<Subscriber>> subscribersCopy = new LinkedList<>();
synchronized (subscribers) {
subscribersCopy.addAll(subscribers);
}
for (WeakReference<Subscriber> subscriber : subscribersCopy) {
if (subscriber.get() != null)
subscriber.get().onTopicPublished(this);
}
@ -86,12 +94,15 @@ public class Topic {
topic.subscribe(this);
}
}
default void unsubscribeTopics() {
for (Topic event : getSubscription()) {
event.unsubscribe(this);
}
}
void onTopicPublished(Topic topic);
Topic[] getSubscription();
}
}