react-native-navigation的迁移库

EventBus.java 1.5KB

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