2017-08-03 16:12:11 +00:00
|
|
|
package com.topjohnwu.magisk.utils;
|
|
|
|
|
|
|
|
import java.lang.ref.WeakReference;
|
|
|
|
import java.util.Iterator;
|
|
|
|
import java.util.LinkedList;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
public class Topic {
|
|
|
|
|
|
|
|
public boolean hasPublished = false;
|
|
|
|
private List<WeakReference<Subscriber>> subscribers;
|
|
|
|
|
|
|
|
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 publish() {
|
2017-10-07 09:12:36 +00:00
|
|
|
publish(true, null);
|
2017-08-03 16:12:11 +00:00
|
|
|
}
|
|
|
|
|
2017-08-28 20:10:04 +00:00
|
|
|
public void publish(boolean record) {
|
2017-10-07 09:12:36 +00:00
|
|
|
publish(record, null);
|
|
|
|
}
|
|
|
|
|
|
|
|
public void publish(boolean record, Object result) {
|
2017-08-28 20:10:04 +00:00
|
|
|
hasPublished = record;
|
2017-08-03 16:12:11 +00:00
|
|
|
if (subscribers != null) {
|
|
|
|
for (WeakReference<Subscriber> subscriber : subscribers) {
|
|
|
|
if (subscriber.get() != null)
|
2017-10-07 09:12:36 +00:00
|
|
|
subscriber.get().onTopicPublished(this, result);
|
2017-08-03 16:12:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public interface Subscriber {
|
|
|
|
default void subscribeTopics() {
|
|
|
|
for (Topic topic : getSubscription()) {
|
|
|
|
if (topic.hasPublished) {
|
|
|
|
onTopicPublished(topic);
|
|
|
|
}
|
|
|
|
topic.subscribe(this);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default void unsubscribeTopics() {
|
|
|
|
for (Topic event : getSubscription()) {
|
|
|
|
event.unsubscribe(this);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default void onTopicPublished() {
|
2017-10-07 09:12:36 +00:00
|
|
|
onTopicPublished(null, null);
|
|
|
|
}
|
|
|
|
default void onTopicPublished(Topic topic) {
|
|
|
|
onTopicPublished(topic, null);
|
2017-08-03 16:12:11 +00:00
|
|
|
}
|
2017-10-07 09:12:36 +00:00
|
|
|
void onTopicPublished(Topic topic, Object result);
|
2017-08-03 16:12:11 +00:00
|
|
|
Topic[] getSubscription();
|
|
|
|
}
|
|
|
|
}
|