@Test(timeout = TIMEOUT) public void onStateChange() { AtomicInteger primaryCounter = new AtomicInteger(0); AtomicInteger secondaryCounter = new AtomicInteger(0); Scoped listener = mSelector.onStateChange(state -> { if (state.equals(State.PRIMARY)) { primaryCounter.incrementAndGet(); } else { secondaryCounter.incrementAndGet(); } }); for (int i = 0; i < 10; i++) { mSelector.setState(State.PRIMARY); mSelector.setState(State.SECONDARY); } assertEquals(10, primaryCounter.get()); assertEquals(10, secondaryCounter.get()); listener.close(); mSelector.setState(State.PRIMARY); mSelector.setState(State.SECONDARY); assertEquals(10, primaryCounter.get()); assertEquals(10, secondaryCounter.get()); }
@Override public final Scoped onStateChange(Consumer<State> listener) { AtomicReference<Consumer<State>> listenerRef = new AtomicReference<>(listener); synchronized (mListeners) { Preconditions.checkState(mListeners.add(listenerRef), "listener already exists"); } return () -> { synchronized (mListeners) { mListeners.remove(listenerRef); } }; }
AbstractPrimarySelector implements PrimarySelector { @Override public final Scoped onStateChange(Consumer<State> listener) { AtomicReference<Consumer<State>> listenerRef = new AtomicReference<>(listener); synchronized (mListeners) { Preconditions.checkState(mListeners.add(listenerRef), "listener already exists"); } return () -> { synchronized (mListeners) { mListeners.remove(listenerRef); } }; } }
AbstractPrimarySelector implements PrimarySelector { @Override public final Scoped onStateChange(Consumer<State> listener) { AtomicReference<Consumer<State>> listenerRef = new AtomicReference<>(listener); synchronized (mListeners) { Preconditions.checkState(mListeners.add(listenerRef), "listener already exists"); } return () -> { synchronized (mListeners) { mListeners.remove(listenerRef); } }; }  }
AbstractPrimarySelector implements PrimarySelector { @Override public final Scoped onStateChange(Consumer<State> listener) { AtomicReference<Consumer<State>> listenerRef = new AtomicReference<>(listener); synchronized (mListeners) { Preconditions.checkState(mListeners.add(listenerRef), "listener already exists"); } return () -> { synchronized (mListeners) { mListeners.remove(listenerRef); } }; }  @Override final State getState(); @Override final Scoped onStateChange(Consumer<State> listener); @Override final void waitForState(State state); }
AbstractPrimarySelector implements PrimarySelector { @Override public final Scoped onStateChange(Consumer<State> listener) { AtomicReference<Consumer<State>> listenerRef = new AtomicReference<>(listener); synchronized (mListeners) { Preconditions.checkState(mListeners.add(listenerRef), "listener already exists"); } return () -> { synchronized (mListeners) { mListeners.remove(listenerRef); } }; }  @Override final State getState(); @Override final Scoped onStateChange(Consumer<State> listener); @Override final void waitForState(State state);  }