mirror of
https://github.com/topjohnwu/Magisk.git
synced 2025-02-26 08:57:25 +00:00
Prevent memory leak in CallbackEvent
This commit is contained in:
parent
72820b162c
commit
73bb0b10ee
@ -1,19 +1,23 @@
|
|||||||
package com.topjohnwu.magisk.utils;
|
package com.topjohnwu.magisk.utils;
|
||||||
|
|
||||||
|
import java.lang.ref.WeakReference;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
public class CallbackEvent<Result> {
|
public class CallbackEvent<Result> {
|
||||||
|
|
||||||
public boolean isTriggered = false;
|
public boolean isTriggered = false;
|
||||||
private Result result;
|
private Result result;
|
||||||
private Set<Listener<Result>> listeners;
|
private List<WeakReference<Listener<Result>>> listeners;
|
||||||
|
|
||||||
public void register(Listener<Result> l) {
|
public void register(Listener<Result> l) {
|
||||||
if (listeners == null) {
|
if (listeners == null) {
|
||||||
listeners = new HashSet<>();
|
listeners = new LinkedList<>();
|
||||||
}
|
}
|
||||||
listeners.add(l);
|
listeners.add(new WeakReference<>(l));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void unRegister() {
|
public void unRegister() {
|
||||||
@ -21,8 +25,11 @@ public class CallbackEvent<Result> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void unRegister(Listener<Result> l) {
|
public void unRegister(Listener<Result> l) {
|
||||||
if (listeners != null) {
|
for (Iterator<WeakReference<Listener<Result>>> i = listeners.iterator(); i.hasNext();) {
|
||||||
listeners.remove(l);
|
WeakReference<Listener<Result>> listener = i.next();
|
||||||
|
if (listener.get() == null || listener.get() == l) {
|
||||||
|
i.remove();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,8 +41,9 @@ public class CallbackEvent<Result> {
|
|||||||
result = r;
|
result = r;
|
||||||
isTriggered = true;
|
isTriggered = true;
|
||||||
if (listeners != null) {
|
if (listeners != null) {
|
||||||
for (Listener<Result> listener : listeners) {
|
for (WeakReference<Listener<Result>> listener : listeners) {
|
||||||
listener.onTrigger(this);
|
if (listener.get() != null)
|
||||||
|
listener.get().onTrigger(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user