RxNamespace { public static Observable<MountEvent> mount(final Observable<Server> rxServer, final String name) { return Observable.switchOnNext( rxServer.map(server -> { final Map<PublisherEntryKey, MountRecord> mountRecords = new HashMap<>(); final PublisherEntry[] mounts = server.getStatus().getPublisherStatus(); final List<MountEvent> alreadyMounted = new ArrayList<>(mounts.length); for (final PublisherEntry status : mounts) { if (status.getName().equals(name)) { mountRecords.put(PublisherEntryKey.fromPublisherEntry(status), MountRecord.fromStatus(status)); if (isAlreadyMounted(status)) { alreadyMounted.add(MountEvent.forStatus(true, status.getName(), status.getServer(), status.getLastMount(), status.getLastMountError() )); } } } if (alreadyMounted.isEmpty()) { try { server.addName(name); } catch (final VException e) { return Observable.just(MountEvent.forAddNameFailure(name, e)); } final MountEvent initial = MountEvent.forAddNameSuccess(name); return RxPublisherState.index( RxPublisherState.poll(server).map(state -> state.filter( status -> status.getName().equals(name)))) .flatMapIterable(Map::entrySet) .concatMap(e -> processStatus(mountRecords, e.getKey(), e.getValue())) .startWith(initial); } else { return Observable.from(alreadyMounted); } })) .takeWhile(MountEvent::isMount); }  static Observable<MountEvent> mount(final Observable<Server> rxServer,
                                                          final String name);  }
@Test public void testAlreadyMounted() { when(mServer.getStatus()).thenReturn(mockStatus(new PublisherEntry("foo", "bar", THE_PAST, null, null, THE_DISTANT_PAST, null))); mSubscriber.expectedEvents.add(MountEvent::isSuccessfulMount); attachSubscriber(RxNamespace.mount(mRxServer, "foo")); }
@Test public void testExistingOtherNames() { when(mServer.getStatus()).thenReturn(mockStatus(new PublisherEntry("baz", "bar", THE_PAST, null, null, THE_DISTANT_PAST, null))); mSubscriber.expectedEvents.add(RxNamespaceTest::isInitialMountAttemptStart); attachSubscriber(RxNamespace.mount(mRxServer, "foo")); }