private static void test4() { log("just subscribe to see output "); Observable<List<Integer>> listOfInts = Observable.just(Arrays.asList(1, 3, 5, 7), Arrays.asList(2, 4, 6, 8)); listOfInts.subscribe(x -> System.out.print(x + " ")); println(""); log("concatMap"); listOfInts.concatMap(x -> Observable.from(x)).subscribe(Main::print); println(""); log("flapMap"); listOfInts .flatMap( listOfIntegers -> { return Observable.from(listOfIntegers); }) .subscribe(Main::print); println(""); Map<String, List<Integer>> m1 = new HashMap<>(); m1.put("key", Arrays.asList(2, 4, 6, 8, 10)); Map<String, List<Integer>> m2 = new HashMap<>(); m2.put("key", Arrays.asList(1, 3, 5, 7, 9)); log("testing flatMap with 2 maps param"); Observable.just(m1, m2) .flatMap(map -> Observable.from(map.get("key")).map(x -> x)) .subscribe(Main::print); println(""); }
@Test public void testEmitNull() { Observable<Integer> oi = Observable.from(1, null, 3); Observable<String> os = Observable.from("a", "b", null); Observable<String> o = Observable.zip( oi, os, new Func2<Integer, String, String>() { @Override public String call(Integer t1, String t2) { return t1 + "-" + t2; } }); final ArrayList<String> list = new ArrayList<String>(); o.subscribe( new Action1<String>() { @Override public void call(String s) { System.out.println(s); list.add(s); } }); assertEquals(3, list.size()); assertEquals("1-a", list.get(0)); assertEquals("null-b", list.get(1)); assertEquals("3-null", list.get(2)); }
public static void test5() { log("test zip of two observables with equal elements from both lists"); Observable.zip( Observable.from(Arrays.asList(1, 3, 5, 7, 9)), Observable.from(Arrays.asList(2, 4, 6, 8, 10)), (x, y) -> "(" + x + "," + y + ")") .subscribe(Main::print); println(""); log("test zipWith with unequal elements from lists"); Observable.from(Arrays.asList(1, 3, 5)) .zipWith(Observable.from(Arrays.asList(2, 4, 6, 7)), (x, y) -> "(" + x + "," + y + ")") .subscribe(Main::print); println(""); log("test retry stuff"); AtomicInteger i = new AtomicInteger(0); Observable<String> testRetry = Observable.create( subs -> { if (i.get() < 3) { i.incrementAndGet(); println("retyring for " + i + " time."); subs.onError(new RuntimeException("error 1")); } else { subs.onNext("hello"); subs.onCompleted(); } }); testRetry.retry().subscribe(Main::print, Main::println); println(""); }
/** IO scheduler defaults to using CachedThreadScheduler */ @Test public final void testIOScheduler() { Observable<Integer> o1 = Observable.from(1, 2, 3, 4, 5); Observable<Integer> o2 = Observable.from(6, 7, 8, 9, 10); Observable<String> o = Observable.merge(o1, o2) .map( new Func1<Integer, String>() { @Override public String call(Integer t) { assertTrue( Thread.currentThread().getName().startsWith("RxCachedThreadScheduler")); return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); } }); o.subscribeOn(Schedulers.io()) .toBlocking() .forEach( new Action1<String>() { @Override public void call(String t) { System.out.println("t: " + t); } }); }
public static void run() { // Terrible query("Gimme some movies!") .subscribe( urls -> { for (String url : urls) { System.out.println(url); } }); // Still terrible query("Gimme some movies!") .subscribe( urls -> { Observable.from(urls).subscribe(url -> System.out.println(url)); }); // Ye olde flatMap! query("Gimme some movies!") .flatMap(urls -> Observable.from(urls)) .subscribe(url -> System.out.println(url)); // Behold the power of flatMap! query("Gimme some movies!") .flatMap(urls -> Observable.from(urls)) .flatMap(url -> getTitle(url)) .subscribe(title -> System.out.println(title)); }
@Test public void testConcatObservableOfObservables() { @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); final String[] o = {"1", "3", "5", "7"}; final String[] e = {"2", "4", "6"}; final Observable<String> odds = Observable.from(o); final Observable<String> even = Observable.from(e); Observable<Observable<String>> observableOfObservables = Observable.create( new Observable.OnSubscribeFunc<Observable<String>>() { @Override public Subscription onSubscribe(Observer<? super Observable<String>> observer) { // simulate what would happen in an observable observer.onNext(odds); observer.onNext(even); observer.onCompleted(); return Subscriptions.empty(); } }); Observable<String> concat = Observable.concat(observableOfObservables); concat.subscribe(observer); verify(observer, times(7)).onNext(anyString()); }
@Test public void testFlatMapTransformsException() { Observable<Integer> onNext = Observable.from(Arrays.asList(1, 2, 3)); Observable<Integer> onCompleted = Observable.from(Arrays.asList(4)); Observable<Integer> onError = Observable.from(Arrays.asList(5)); Observable<Integer> source = Observable.concat( Observable.from(Arrays.asList(10, 20, 30)), Observable.<Integer>error(new RuntimeException("Forced failure!"))); @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); source.flatMap(just(onNext), just(onError), just0(onCompleted)).subscribe(o); verify(o, times(3)).onNext(1); verify(o, times(3)).onNext(2); verify(o, times(3)).onNext(3); verify(o).onNext(5); verify(o).onCompleted(); verify(o, never()).onNext(4); verify(o, never()).onError(any(Throwable.class)); }
public void testSplit(String str, String regex, int limit, String... parts) { testSplit(str, regex, 0, Observable.from(str), parts); for (int i = 0; i < str.length(); i++) { String a = str.substring(0, i); String b = str.substring(i, str.length()); testSplit(a + "|" + b, regex, limit, Observable.from(a, b), parts); } }
@Test public void testOnNextExceptionInvokesOnError() { Func2<Integer, Integer, Integer> zipr = getDivideZipr(); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); Observable<Integer> w = Observable.zip(Observable.from(10, 20, 30), Observable.from(0, 1, 2), zipr); w.subscribe(observer); verify(observer, times(1)).onError(any(Throwable.class)); }
private Observable<Item> searchByHashtagObservable() { Observable<Item> observableSocialNetworks = Observable.from(socialNetworks) .flatMap( new Func1<SocialNetwork, Observable<Item>>() { @Override public Observable<Item> call(SocialNetwork socialNetwork) { return socialNetwork.getService().searchByHashtag(hashtag); } }); List<Observable<Item>> observableList = Lists.newArrayList(); observableList.add(observableSocialNetworks); return Observable.zip( observableList, new FuncN<Item>() { @Override public Item call(Object... args) { if (args.length == 1) { return (Item) args[0]; } return Item.empty(); } }); }
public Observable<List<TwitterUser>> searchUsers(String prefix) { if (ThreadLocalRandom.current().nextDouble() < failureProbability) { return Observable.error(new IOException("Broken pipe")); } return Observable.from(users).skip(1).toList().subscribeOn(Schedulers.newThread()); }
private void loadList(List<AppInfo> apps) { mRecyclerView.setVisibility(View.VISIBLE); Observable.from(Lists.reverse(apps)) .scan( (appInfo, appInfo2) -> { if (appInfo.getName().length() > appInfo2.getName().length()) { return appInfo; } else { return appInfo2; } }) .distinct() .subscribe( new Observer<AppInfo>() { @Override public void onCompleted() { mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { Toast.makeText(getActivity(), "Something went south!", Toast.LENGTH_SHORT).show(); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onNext(AppInfo appInfo) { mAddedApps.add(appInfo); mAdapter.addApplication(mAddedApps.size() - 1, appInfo); } }); }
@Test public void testNormal() { @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); final List<Integer> list = Arrays.asList(1, 2, 3); Func1<Integer, List<Integer>> func = new Func1<Integer, List<Integer>>() { @Override public List<Integer> call(Integer t1) { return list; } }; Func2<Integer, Integer, Integer> resFunc = new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 | t2; } }; List<Integer> source = Arrays.asList(16, 32, 64); Observable.from(source).flatMapIterable(func, resFunc).subscribe(o); for (Integer s : source) { for (Integer v : list) { verify(o).onNext(s | v); } } verify(o).onCompleted(); verify(o, never()).onError(any(Throwable.class)); }
@Test public void testResumeNext() { Subscription s = mock(Subscription.class); // Trigger failure on second element TestObservable f = new TestObservable(s, "one", "fail", "two", "three"); Observable<String> w = Observable.create(f); Observable<String> resume = Observable.from("twoResume", "threeResume"); Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume)); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); }
private Observable<WebPageEntity> parseDocument(DownloadResult downloadResult) { Set<WebPageEntity> result = new HashSet<>(1); Document document = downloadResult.getDocument(); if (document != null) { Elements elements = document.select(".InfoArea a[title]"); if (!elements.isEmpty()) { for (Element element : elements) { WebPageEntity webPageEntity = new WebPageEntity( downloadResult.getSourcePage(), "", "productPage", element.attr("abs:href"), downloadResult.getSourcePage().getCategory()); LOGGER.info("productPageUrl={}", webPageEntity.getUrl()); result.add(webPageEntity); } } else { WebPageEntity webPageEntity = new WebPageEntity( downloadResult.getSourcePage(), "", "productPage", downloadResult.getSourcePage().getUrl(), downloadResult.getSourcePage().getCategory()); LOGGER.info("productPageUrl={}", webPageEntity.getUrl()); result.add(webPageEntity); } } return Observable.from(result); }
@Test public void testBackpressureWithTakeBefore() { final AtomicInteger generated = new AtomicInteger(); Observable<Integer> observable = Observable.from( new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public void remove() {} @Override public Integer next() { return generated.getAndIncrement(); } @Override public boolean hasNext() { return true; } }; } }); TestSubscriber<Integer> testSubscriber = new TestSubscriber<Integer>(); observable.take(7).observeOn(Schedulers.newThread()).subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); testSubscriber.assertReceivedOnNext(Arrays.asList(0, 1, 2, 3, 4, 5, 6)); assertEquals(7, generated.get()); }
private void loadList(List<AppInfo> apps) { mRecyclerView.setVisibility(View.VISIBLE); Observable<AppInfo> observableApp = Observable.from(apps); Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS); Observable.zip(observableApp, tictoc, this::updateTitle) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Observer<AppInfo>() { @Override public void onCompleted() { Toast.makeText(getActivity(), "Here is the list!", Toast.LENGTH_LONG).show(); } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show(); } @Override public void onNext(AppInfo appInfo) { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } mAddedApps.add(appInfo); int position = mAddedApps.size() - 1; mAdapter.addApplication(position, appInfo); mRecyclerView.smoothScrollToPosition(position); } }); }
@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 testResultFunctionThrows() { @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); final List<Integer> list = Arrays.asList(1, 2, 3); Func1<Integer, List<Integer>> func = new Func1<Integer, List<Integer>>() { @Override public List<Integer> call(Integer t1) { return list; } }; Func2<Integer, Integer, Integer> resFunc = new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { throw new TestException(); } }; List<Integer> source = Arrays.asList(16, 32, 64); Observable.from(source).flatMapIterable(func, resFunc).subscribe(o); verify(o, never()).onCompleted(); verify(o, never()).onNext(any()); verify(o).onError(any(TestException.class)); }
public void testSplit( String message, String regex, int limit, Observable<String> src, String... parts) { Observable<String> act = StringObservable.split(src, regex); Observable<String> exp = Observable.from(parts); AssertObservable.assertObservableEqualsBlocking( "when input is " + message + " and limit = " + limit, exp, act); }
@Test public void testMultibyteSpanningTwoBuffers() { Observable<byte[]> src = Observable.from(new byte[] {(byte) 0xc2}, new byte[] {(byte) 0xa1}); String out = StringObservable.decode(src, "UTF-8").toBlockingObservable().single(); assertEquals("\u00A1", out); }
@Test public void testFlatMapTransformsOnNextFuncThrows() { Observable<Integer> onCompleted = Observable.from(Arrays.asList(4)); Observable<Integer> onError = Observable.from(Arrays.asList(5)); Observable<Integer> source = Observable.from(Arrays.asList(10, 20, 30)); @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); source.flatMap(funcThrow(1, onError), just(onError), just0(onCompleted)).subscribe(o); verify(o).onError(any(TestException.class)); verify(o, never()).onNext(any()); verify(o, never()).onCompleted(); }
@Test public void thatPlaneInfoIsSummedUpCombinedWithObservables() throws Exception { WaitMonitor monitor = new WaitMonitor(); // error handler function Action1<Throwable> exceptionConsumer = (e) -> { e.printStackTrace(); monitor.complete(); }; String[] planeTypes = {"Boeing 777", "Boeing 747", "Boeing 737", "Airbus A330"}; Observable.from(planeTypes) .flatMap(this::fetchArticle) .map(this::parsePlaneInfo) .subscribe( (planeInfo) -> { Summary.printCounter(planeInfo.typeName, planeInfo.numberBuild); }, exceptionConsumer, monitor::complete); monitor.waitFor(10000, TimeUnit.MILLISECONDS); }
@Test public void testTimeoutSelectorFirstObservableThrows() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> timeout = PublishSubject.create(); Func1<Integer, Observable<Integer>> timeoutFunc = new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t1) { return timeout; } }; Func0<Observable<Integer>> firstTimeoutFunc = new Func0<Observable<Integer>>() { @Override public Observable<Integer> call() { return Observable.<Integer>error(new OperationReduceTest.CustomException()); } }; Observable<Integer> other = Observable.from(Arrays.asList(100)); @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); source.timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(o); verify(o).onError(any(OperationReduceTest.CustomException.class)); verify(o, never()).onNext(any()); verify(o, never()).onCompleted(); }
private void callWithFrom() { Log.v("Eg:NewActivity:95", "callWithFrom"); Observable.from(getList()) .map( new Func1<String, String>() { @Override public String call(String s) { Log.i("Eg:NewActivity:101", "call s -> " + s); return s + " Egis"; } }) .subscribe( new Subscriber<String>() { @Override public void onCompleted() { Log.i("Eg:NewActivity:108", "onCompleted"); } @Override public void onError(Throwable e) { Log.e("Eg:NewActivity:114", "onError"); } @Override public void onNext(String s) { Log.w("Eg:NewActivity:120", "onNext s -> " + s); } }); }
@Test public void testMergeError() { @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); Func1<Integer, Observable<Integer>> func = new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t1) { return Observable.error(new TestException()); } }; Func2<Integer, Integer, Integer> resFunc = new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 | t2; } }; List<Integer> source = Arrays.asList(16, 32, 64); Observable.from(source).flatMap(func, resFunc).subscribe(o); verify(o, never()).onCompleted(); verify(o, never()).onNext(any()); verify(o).onError(any(TestException.class)); }
@Test public void loadRepoWithNEvent() { when(repo.getModificationId()).thenReturn("modif id"); IEvent first = mock(IEvent.class); IEvent second = mock(IEvent.class); IEvent third = mock(IEvent.class); // stub sorting order when(first.compareTo(second)).thenReturn(-1); when(first.compareTo(third)).thenReturn(-1); when(second.compareTo(first)).thenReturn(1); when(second.compareTo(third)).thenReturn(-1); when(third.compareTo(first)).thenReturn(1); when(third.compareTo(second)).thenReturn(1); // pass the events not sorted: List<IEvent> events = Arrays.asList(second, first, third); when(repo.getEventsSubscribedOnProperScheduler()).thenReturn(Observable.from(events)); sut.loadEvents(false, callback); // verify we received them in order List<IEvent> sortedEvents = Arrays.asList(first, second, third); verify(callback).onEventsLoadingStarted("modif id"); verify(callback).onEventsLoadingFinished(sortedEvents, "modif id"); }
@Override public void onClick(View v) { if (v.getId() == R.id.btn_obdervable_test1) { if (RxBus.hasObservers()) { RxBus.send(new TapEvent()); } } else if (v.getId() == R.id.btn_obdervable_test2) { if (RxBus.hasObservers()) { mRemoteServerEngine .loadMoreDataRx(1) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .flatMap(refreshModels -> Observable.from(refreshModels)) .filter(refreshModel -> !refreshModel.title.contains("4")) .take(3) .observeOn(AndroidSchedulers.mainThread()) .subscribe( refreshModel -> { if (RxBus.hasObservers()) { RxBus.send(new RefreshModelEvent(refreshModel)); } }); } } }
@Test public void testTimeoutSelectorTimeoutFirst() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> timeout = PublishSubject.create(); Func1<Integer, Observable<Integer>> timeoutFunc = new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t1) { return timeout; } }; Func0<Observable<Integer>> firstTimeoutFunc = new Func0<Observable<Integer>>() { @Override public Observable<Integer> call() { return timeout; } }; Observable<Integer> other = Observable.from(Arrays.asList(100)); @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); InOrder inOrder = inOrder(o); source.timeout(firstTimeoutFunc, timeoutFunc, other).subscribe(o); timeout.onNext(1); inOrder.verify(o).onNext(100); inOrder.verify(o).onCompleted(); verify(o, never()).onError(any(Throwable.class)); }
public AbstractLoadBalancer<String, String> setup( Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory, LoadBalancerStrategy<HostConnectionProvider<String, String>> loadBalancingStratgey, List<Instance<SocketAddress>> hosts) { this.hosts = Observable.from(hosts); this.eventListenerFactory = eventListenerFactory; this.loadBalancingStratgey = loadBalancingStratgey; if (null != lbFactory) { loadBalancer = lbFactory.call(this.hosts, eventListenerFactory, loadBalancingStratgey); return loadBalancer; } loadBalancer = new AbstractLoadBalancer<String, String>( this.hosts, eventListenerFactory, loadBalancingStratgey) { @Override protected ConnectionProvider<String, String> newConnectionProviderForHost( final Instance<SocketAddress> host, final ConnectionFactory<String, String> connectionFactory) { return new ConnectionProvider<String, String>(connectionFactory) { @Override public ConnectionObservable<String, String> nextConnection() { return connectionFactory.newConnection(host.getValue()); } }; } }; return getLoadBalancer(); }