Magisk/app/src/main/java/com/topjohnwu/magisk/utils/Topic.java

76 lines
2.1 KiB
Java
Raw Normal View History

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);
}
public void publish(boolean record) {
2017-10-07 09:12:36 +00:00
publish(record, null);
}
public void publish(boolean record, Object result) {
hasPublished = record;
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);
}
}
}
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-10-07 09:12:36 +00:00
void onTopicPublished(Topic topic, Object result);
Topic[] getSubscription();
}
}