@Test public void testParallelMerge() { PublishSubject<String> p1 = PublishSubject.<String>create(); PublishSubject<String> p2 = PublishSubject.<String>create(); PublishSubject<String> p3 = PublishSubject.<String>create(); PublishSubject<String> p4 = PublishSubject.<String>create(); Observable<Observable<String>> fourStreams = Observable.<Observable<String>>from(p1, p2, p3, p4); Observable<Observable<String>> twoStreams = Observable.parallelMerge(fourStreams, 2); Observable<Observable<String>> threeStreams = Observable.parallelMerge(fourStreams, 3); List<? super Observable<String>> fourList = fourStreams.toList().toBlocking().last(); List<? super Observable<String>> threeList = threeStreams.toList().toBlocking().last(); List<? super Observable<String>> twoList = twoStreams.toList().toBlocking().last(); System.out.println("two list: " + twoList); System.out.println("three list: " + threeList); System.out.println("four list: " + fourList); assertEquals(4, fourList.size()); assertEquals(3, threeList.size()); assertEquals(2, twoList.size()); }
@Test public void testNumberOfThreads() { final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>(); // parallelMerge into 3 streams and observeOn for each // we expect 3 threads in the output Observable.parallelMerge(getStreams(), 3) .flatMap( new Func1<Observable<String>, Observable<String>>() { @Override public Observable<String> call(Observable<String> o) { // for each of the parallel return o.observeOn(Schedulers.newThread()); } }) .toBlocking() .forEach( new Action1<String>() { @Override public void call(String o) { System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId()); threads.put(Thread.currentThread().getId(), Thread.currentThread().getId()); } }); assertTrue( threads.keySet().size() <= 3); // can be less than since merge doesn't block threads and may not use all of them }