|
@@ -1,31 +1,44 @@
|
1
|
1
|
package com.reactnativenavigation.events;
|
2
|
2
|
|
|
3
|
+import java.lang.ref.WeakReference;
|
3
|
4
|
import java.util.ArrayList;
|
4
|
5
|
import java.util.List;
|
5
|
6
|
|
6
|
7
|
public enum EventBus {
|
7
|
8
|
instance;
|
8
|
9
|
|
9
|
|
- List<Subscriber> subscribers;
|
10
|
|
-
|
11
|
|
- EventBus() {
|
12
|
|
- subscribers = new ArrayList<>();
|
13
|
|
- }
|
|
10
|
+ private final List<WeakReference<Subscriber>> subscribers = new ArrayList<>();
|
14
|
11
|
|
15
|
12
|
public void register(Subscriber subscriber) {
|
16
|
|
- if (subscribers.contains(subscriber)) {
|
17
|
|
- throw new RuntimeException("Subscriber already registered");
|
18
|
|
- }
|
19
|
|
- subscribers.add(subscriber);
|
|
13
|
+ if (isSubscribed(subscriber)) return;
|
|
14
|
+ subscribers.add(new WeakReference<>(subscriber));
|
20
|
15
|
}
|
21
|
16
|
|
22
|
17
|
public void unregister(Subscriber subscriber) {
|
23
|
|
- subscribers.remove(subscriber);
|
|
18
|
+ for (WeakReference<Subscriber> ref : subscribers) {
|
|
19
|
+ Subscriber registered = ref.get();
|
|
20
|
+ if (registered != null && registered == subscriber) {
|
|
21
|
+ subscribers.remove(ref);
|
|
22
|
+ }
|
|
23
|
+ }
|
24
|
24
|
}
|
25
|
25
|
|
26
|
26
|
public void post(Event event) {
|
27
|
|
- for (Subscriber subscriber : subscribers) {
|
28
|
|
- subscriber.onEvent(event);
|
|
27
|
+ for (WeakReference<Subscriber> ref : subscribers) {
|
|
28
|
+ Subscriber registered = ref.get();
|
|
29
|
+ if (registered != null) {
|
|
30
|
+ registered.onEvent(event);
|
|
31
|
+ }
|
|
32
|
+ }
|
|
33
|
+ }
|
|
34
|
+
|
|
35
|
+ public boolean isSubscribed(Subscriber subscriber) {
|
|
36
|
+ for (WeakReference<Subscriber> ref : subscribers) {
|
|
37
|
+ Subscriber registered = ref.get();
|
|
38
|
+ if (registered != null && registered.equals(subscriber)) {
|
|
39
|
+ return true;
|
|
40
|
+ }
|
29
|
41
|
}
|
|
42
|
+ return false;
|
30
|
43
|
}
|
31
|
44
|
}
|