rx.observables.GroupedObservable Java Examples

The following examples show how to use rx.observables.GroupedObservable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 6 votes vote down vote up
private static <K, V> Map<K, Collection<V>> toMap(Observable<GroupedObservable<K, V>> observable) {

        final ConcurrentHashMap<K, Collection<V>> result = new ConcurrentHashMap<K, Collection<V>>();

        observable.toBlocking().forEach(new Action1<GroupedObservable<K, V>>() {

            @Override
            public void call(final GroupedObservable<K, V> o) {
                result.put(o.getKey(), new ConcurrentLinkedQueue<V>());
                o.subscribe(new Action1<V>() {

                    @Override
                    public void call(V v) {
                        result.get(o.getKey()).add(v);
                    }

                });
            }
        });

        return result;
    }
 
Example #2
Source File: GroupConcat.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.setProperty("rx.ring-buffer.size", "16");

    List<AppInfo> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 3; j++) {
            AppInfo ai = new AppInfo();
            ai.name = i + " - " + j;
            ai.date = LocalDate.of(2016, 3, i + 1);
            list.add(ai);
        }
    }

    Observable<GroupedObservable<String, AppInfo>> o = Observable.from(list)
    .groupBy(v -> v.date.format(DateTimeFormatter.ofPattern("MM/yyyy")));

    Observable.concat(o)
    .subscribe(System.out::println);
}
 
Example #3
Source File: DynamicConnectionSet.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> DynamicConnectionSet<GroupedObservable<K, V>> create(
        final ConnectToGroupedObservable.Builder<K, V> config, int maxTimeBeforeDisconnectSec) {
    Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<GroupedObservable<K, V>>> toObservableFunc = new
            Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<GroupedObservable<K, V>>>() {
                @Override
                public RemoteRxConnection<GroupedObservable<K, V>> call(Endpoint endpoint, Action0 disconnectCallback,
                                                                        PublishSubject<Integer> closeConnectionTrigger) {
                    // copy config, change host, port and id
                    ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config);
                    configCopy
                            .host(endpoint.getHost())
                            .port(endpoint.getPort())
                            .closeTrigger(closeConnectionTrigger)
                            .connectionDisconnectCallback(disconnectCallback)
                            .slotId(endpoint.getSlotId());
                    return RemoteObservable.connect(configCopy.build());
                }
            };
    return new DynamicConnectionSet<GroupedObservable<K, V>>(toObservableFunc, MIN_TIME_SEC_DEFAULT, maxTimeBeforeDisconnectSec);
}
 
Example #4
Source File: DynamicConnection.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> DynamicConnection<GroupedObservable<K, V>> create(
        final ConnectToGroupedObservable.Builder<K, V> config, Observable<Endpoint> endpoints) {
    Func1<Endpoint, Observable<GroupedObservable<K, V>>> toObservableFunc = new
            Func1<Endpoint, Observable<GroupedObservable<K, V>>>() {
                @Override
                public Observable<GroupedObservable<K, V>> call(Endpoint endpoint) {
                    // copy config, change host, port and id
                    ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config);
                    configCopy
                            .host(endpoint.getHost())
                            .port(endpoint.getPort())
                            .slotId(endpoint.getSlotId());
                    return RemoteObservable.connect(configCopy.build()).getObservable();
                }
            };
    return new DynamicConnection<GroupedObservable<K, V>>(toObservableFunc, endpoints);
}
 
Example #5
Source File: PushServers.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> LegacyTcpPushServer<KeyValuePair<K, V>> infiniteStreamLegacyTcpNestedGroupedObservable(ServerConfig<KeyValuePair<K, V>> config,
                                                                                                            Observable<Observable<GroupedObservable<K, V>>> go,
                                                                                                            long groupExpirySeconds, final Func1<K, byte[]> keyEncoder,
                                                                                                            HashFunction hashFunction) {
    final PublishSubject<String> serverSignals = PublishSubject.create();
    final String serverName = config.getName();
    Action0 onComplete = new Action0() {
        @Override
        public void call() {
            serverSignals.onNext("ILLEGAL_STATE_COMPLETED");
            throw new IllegalStateException("OnComplete signal received, Server: " + serverName + " is pushing an infinite stream, should not complete");
        }
    };

    Action1<Throwable> onError = new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            serverSignals.onError(t);
        }
    };

    PushTrigger<KeyValuePair<K, V>> trigger = ObservableTrigger.oogo(serverName, go, onComplete, onError, groupExpirySeconds,
            keyEncoder, hashFunction);
    return new LegacyTcpPushServer<KeyValuePair<K, V>>(trigger, config, serverSignals);
}
 
Example #6
Source File: RemoteObservable.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> RemoteRxConnection<GroupedObservable<K, V>> connect(
        final ConnectToGroupedObservable<K, V> config) {
    final RxMetrics metrics = new RxMetrics();
    return new RemoteRxConnection<GroupedObservable<K, V>>(Observable.create(
            new OnSubscribe<GroupedObservable<K, V>>() {
                @Override
                public void call(Subscriber<? super GroupedObservable<K, V>> subscriber) {
                    RemoteUnsubscribe remoteUnsubscribe = new RemoteUnsubscribe(config.getName());
                    // wrapped in Observable.create() to inject unsubscribe callback
                    subscriber.add(remoteUnsubscribe); // unsubscribed callback
                    // create connection
                    createTcpConnectionToServer(config, remoteUnsubscribe, metrics,
                            config.getConnectionDisconnectCallback(),
                            config.getCloseTrigger())
                            .retryWhen(retryLogic(config))
                            .subscribe(subscriber);
                }
            }), metrics, config.getCloseTrigger());
}
 
Example #7
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupByOnAsynchronousSourceAcceptsMultipleSubscriptions() throws InterruptedException {

    // choose an asynchronous source
    Observable<Long> source = Observable.interval(10, TimeUnit.MILLISECONDS).take(1);

    // apply groupBy to the source
    Observable<GroupedObservable<Boolean, Long>> stream = source.groupBy(IS_EVEN);

    // create two observers
    @SuppressWarnings("unchecked")
    Observer<GroupedObservable<Boolean, Long>> o1 = mock(Observer.class);
    @SuppressWarnings("unchecked")
    Observer<GroupedObservable<Boolean, Long>> o2 = mock(Observer.class);

    // subscribe with the observers
    stream.subscribe(o1);
    stream.subscribe(o2);

    // check that subscriptions were successful
    verify(o1, never()).onError(Matchers.<Throwable>any());
    verify(o2, never()).onError(Matchers.<Throwable>any());
}
 
Example #8
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
/**
 * Assert we get an IllegalStateException if trying to subscribe to an inner GroupedObservable more than once
 */
@Test
public void testExceptionIfSubscribeToChildMoreThanOnce() {
    Observable<Integer> source = Observable.just(0);

    final AtomicReference<GroupedObservable<Integer, Integer>> inner = new AtomicReference<GroupedObservable<Integer, Integer>>();

    Observable<GroupedObservable<Integer, Integer>> m = source.groupBy(identity, dbl);

    m.subscribe(new Action1<GroupedObservable<Integer, Integer>>() {
        @Override
        public void call(GroupedObservable<Integer, Integer> t1) {
            inner.set(t1);
        }
    });

    inner.get().subscribe();

    @SuppressWarnings("unchecked")
    Observer<Integer> o2 = mock(Observer.class);

    inner.get().subscribe(o2);

    verify(o2, never()).onCompleted();
    verify(o2, never()).onNext(anyInt());
    verify(o2).onError(any(IllegalStateException.class));
}
 
Example #9
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupBy() {
    Observable<String> source = Observable.just("one", "two", "three", "four", "five", "six");
    Observable<GroupedObservable<Integer, String>> grouped = source.lift(new OperatorGroupBy<String, Integer, String>(length));

    Map<Integer, Collection<String>> map = toMap(grouped);

    assertEquals(3, map.size());
    assertArrayEquals(Arrays.asList("one", "two", "six").toArray(), map.get(3).toArray());
    assertArrayEquals(Arrays.asList("four", "five").toArray(), map.get(4).toArray());
    assertArrayEquals(Arrays.asList("three").toArray(), map.get(5).toArray());
}
 
Example #10
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByWithElementSelector2() {
    Observable<String> source = Observable.just("one", "two", "three", "four", "five", "six");
    Observable<GroupedObservable<Integer, Integer>> grouped = source.groupBy(length, length);

    Map<Integer, Collection<Integer>> map = toMap(grouped);

    assertEquals(3, map.size());
    assertArrayEquals(Arrays.asList(3, 3, 3).toArray(), map.get(3).toArray());
    assertArrayEquals(Arrays.asList(4, 4).toArray(), map.get(4).toArray());
    assertArrayEquals(Arrays.asList(5).toArray(), map.get(5).toArray());
}
 
Example #11
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmpty() {
    Observable<String> source = Observable.empty();
    Observable<GroupedObservable<Integer, String>> grouped = source.lift(new OperatorGroupBy<String, Integer, String>(length));

    Map<Integer, Collection<String>> map = toMap(grouped);

    assertTrue(map.isEmpty());
}
 
Example #12
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testCompletionIfInnerNotSubscribed() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger eventCounter = new AtomicInteger();
    Observable.range(0, 100)
            .groupBy(new Func1<Integer, Integer>() {

                @Override
                public Integer call(Integer i) {
                    return i % 2;
                }
            })
            .subscribe(new Subscriber<GroupedObservable<Integer, Integer>>() {

                @Override
                public void onCompleted() {
                    latch.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    latch.countDown();
                }

                @Override
                public void onNext(GroupedObservable<Integer, Integer> s) {
                    eventCounter.incrementAndGet();
                    System.out.println("=> " + s);
                }
            });
    if (!latch.await(500, TimeUnit.MILLISECONDS)) {
        fail("timed out - never got completion");
    }
    assertEquals(2, eventCounter.get());
}
 
Example #13
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByBackpressure() throws InterruptedException {

    TestSubscriber<String> ts = new TestSubscriber<String>();

    Observable.range(1, 4000)
            .groupBy(IS_EVEN2)
            .flatMap(new Func1<GroupedObservable<Boolean, Integer>, Observable<String>>() {

                @Override
                public Observable<String> call(final GroupedObservable<Boolean, Integer> g) {
                    return g.observeOn(Schedulers.computation()).map(new Func1<Integer, String>() {

                        @Override
                        public String call(Integer l) {
                            if (g.getKey()) {
                                try {
                                    Thread.sleep(1);
                                } catch (InterruptedException e) {
                                }
                                return l + " is even.";
                            } else {
                                return l + " is odd.";
                            }
                        }

                    });
                }

            }).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
}
 
Example #14
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByWithElementSelector() {
    Observable<String> source = Observable.just("one", "two", "three", "four", "five", "six");
    Observable<GroupedObservable<Integer, Integer>> grouped = source.lift(new OperatorGroupBy<String, Integer, Integer>(length, length));

    Map<Integer, Collection<Integer>> map = toMap(grouped);

    assertEquals(3, map.size());
    assertArrayEquals(Arrays.asList(3, 3, 3).toArray(), map.get(3).toArray());
    assertArrayEquals(Arrays.asList(4, 4).toArray(), map.get(4).toArray());
    assertArrayEquals(Arrays.asList(5).toArray(), map.get(5).toArray());
}
 
Example #15
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testgroupByBackpressure2() throws InterruptedException {

    TestSubscriber<String> ts = new TestSubscriber<String>();

    Observable.range(1, 4000).groupBy(IS_EVEN2).flatMap(new Func1<GroupedObservable<Boolean, Integer>, Observable<String>>() {

        @Override
        public Observable<String> call(final GroupedObservable<Boolean, Integer> g) {
            return g.take(2).observeOn(Schedulers.computation()).map(new Func1<Integer, String>() {

                @Override
                public String call(Integer l) {
                    if (g.getKey()) {
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                        }
                        return l + " is even.";
                    } else {
                        return l + " is odd.";
                    }
                }

            });
        }

    }).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertNoErrors();
}
 
Example #16
Source File: InMemoryGroupbyTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
/**
 * This does the same thing as {@link #groupByInMemory_MoreDetail()} but with pedagogical details
 * @throws Exception
 */
@Test(groups = "samples", timeOut = TIMEOUT)
public void groupByInMemory_MoreDetail() {

    int requestPageSize = 3;
    FeedOptions options = new FeedOptions();
    options.setMaxItemCount(requestPageSize);


    Observable<Document> documentsObservable = client
            .queryDocuments(getCollectionLink(),
                    new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id",
                            new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))),
                    options)
            .flatMap(page -> Observable.from(page.getResults()));

    final LocalDateTime now = LocalDateTime.now();

    Observable<GroupedObservable<Integer, Document>> groupedByPayerIdObservable = documentsObservable
            .filter(doc -> Math.abs(now.getSecond() - doc.getInt("created_time")) <= 90)
            .groupBy(doc -> doc.getInt("payer_id"));

    Observable<List<Document>> docsGroupedAsList = groupedByPayerIdObservable.flatMap(grouped -> {
        Observable<List<Document>> list = grouped.toList();
        return list;
    });

    List<List<Document>> resultsGroupedAsLists = docsGroupedAsList.toList().toBlocking().single();

    for(List<Document> resultsForEachPayer : resultsGroupedAsLists) {
        System.out.println("documents with payer_id : " + resultsForEachPayer.get(0).getInt("payer_id") + " are " + resultsForEachPayer);
    }
}
 
Example #17
Source File: FileObservable.java    From rxjava-file with Apache License 2.0 5 votes vote down vote up
private static Func1<GroupedObservable<Boolean, ?>, Observable<?>> sampleIfTrue(
        final long sampleTimeMs) {
    return new Func1<GroupedObservable<Boolean, ?>, Observable<?>>() {

        @Override
        public Observable<?> call(GroupedObservable<Boolean, ?> group) {
            // if is modify or overflow WatchEvent
            if (group.getKey())
                return group.sample(sampleTimeMs, TimeUnit.MILLISECONDS);
            else
                return group;
        }
    };
}
 
Example #18
Source File: GroupedObservableUtils.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static <K, T> GroupedObservable<K, T> createGroupedObservable(K key, final Observable<T> o) {
    return GroupedObservable.create(key, new OnSubscribe<T>() {

        @Override
        public void call(Subscriber<? super T> s) {
            o.unsafeSubscribe(s);
        }
    });
}
 
Example #19
Source File: ObservableTrigger.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static <K, V> PushTrigger<KeyValuePair<K, V>> oogo(String name, final Observable<Observable<GroupedObservable<K, V>>> oo,
                                                          Action0 doOnComplete,
                                                          Action1<Throwable> doOnError,
                                                          long groupExpirySeconds,
                                                          final Func1<K, byte[]> keyEncoder,
                                                          HashFunction hashFunction) {
    return groupTrigger(name, Observable.merge(oo), doOnComplete, doOnError, groupExpirySeconds, keyEncoder, hashFunction);
}
 
Example #20
Source File: FixedConnectionSet.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static <K, V> FixedConnectionSet<GroupedObservable<K, V>> create(int expectedTerminalCount,
                                                                        final ConnectToGroupedObservable.Builder<K, V> config, EndpointInjector endpointService) {
    Func1<Endpoint, Observable<GroupedObservable<K, V>>> toObservableFunc = new
            Func1<Endpoint, Observable<GroupedObservable<K, V>>>() {
                @Override
                public Observable<GroupedObservable<K, V>> call(Endpoint endpoint) {
                    config.host(endpoint.getHost())
                            .port(endpoint.getPort());
                    return RemoteObservable.connect(config.build()).getObservable();
                }
            };
    return new FixedConnectionSet<GroupedObservable<K, V>>(expectedTerminalCount, endpointService, toObservableFunc);
}
 
Example #21
Source File: StageExecutors.java    From mantis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <K, T, R> Observable<Observable<R>> executeGroupsInParallel(Observable<GroupedObservable<K, T>> go,
                                                                           final Computation computation, final Context context, final long groupTakeUntil) {
    logger.info("initializing {}", computation.getClass().getCanonicalName());
    computation.init(context);

    // from groups to observable
    final Func2<Context, GroupedObservable<K, T>, Observable<R>> c
            = (Func2<Context, GroupedObservable<K, T>, Observable<R>>) computation;
    return
            go
                    .lift(new MonitorOperator<>("worker_stage_outer"))
                    .map((Func1<GroupedObservable<K, T>, Observable<R>>) group -> c
                            .call(context, GroupedObservableUtils.createGroupedObservable(group.getKey(),
                                    group
                                            // comment out as it induces NPE in merge supposedly fixed in rxJava 1.0
                                            .doOnUnsubscribe(() -> {
                                                //logger.info("Expiring group in executeGroupsInParallel" + group.getKey());
                                                if (groupsExpiredCounter != null)
                                                    groupsExpiredCounter.increment();
                                            })
                                            .timeout(groupTakeUntil, TimeUnit.SECONDS, (Observable<? extends T>) Observable.empty())

                                            .subscribeOn(Schedulers.computation())

                                            .lift(new MonitorOperator<T>("worker_stage_inner_input"))))
                            .lift(new MonitorOperator("worker_stage_inner_output")));
}
 
Example #22
Source File: StageExecutors.java    From mantis with Apache License 2.0 5 votes vote down vote up
private static <K, T, R> Observable<Observable<GroupedObservable<String, R>>> setupScalarToKeyStage(ScalarToKey<K, T, R> stage,
                                                                                                    Observable<Observable<T>> source, Context context) {
    StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy();
    logger.info("Setting up ScalarToKey stage with input type: " + inputType);
    // check if job overrides the default input strategy
    if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) {
        return executeInnersInParallel(source, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds(), resolveStageConcurrency(stage.getConcurrency()));
    } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) {
        Observable<Observable<T>> merged = Observable.just(Observable.merge(source));
        return executeInners(merged, stage.getComputation(), context, true, stage.getKeyExpireTimeSeconds());
    } else {
        throw new RuntimeException("Unsupported input type: " + inputType.name());
    }
}
 
Example #23
Source File: StageExecutors.java    From mantis with Apache License 2.0 5 votes vote down vote up
private static <K1, T, K2, R> Observable<Observable<GroupedObservable<String, R>>> setupKeyToKeyStage(KeyToKey<K1, T, K2, R> stage,
                                                                                                      Observable<Observable<GroupedObservable<String, T>>> source, Context context) {
    StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy();
    logger.info("Setting up KeyToKey stage with input type: " + inputType);
    // check if job overrides the default input strategy
    if (inputType == StageConfig.INPUT_STRATEGY.CONCURRENT) {
        throw new RuntimeException("Concurrency is not a supported input strategy for KeyComputation");
    } else if (inputType == StageConfig.INPUT_STRATEGY.SERIAL) {
        Observable<GroupedObservable<String, T>> shuffled = Groups.flatten(source);
        return executeGroupsInParallel(shuffled, stage.getComputation(), context, stage.getKeyExpireTimeSeconds());
    } else {
        throw new RuntimeException("Unsupported input type: " + inputType.name());
    }
}
 
Example #24
Source File: StageExecutors.java    From mantis with Apache License 2.0 5 votes vote down vote up
private static <K, T, R> Observable<Observable<R>> setupKeyToScalarStage(KeyToScalar<K, T, R> stage,
                                                                         Observable<Observable<MantisGroup<String, T>>> source, Context context) {
    StageConfig.INPUT_STRATEGY inputType = stage.getInputStrategy();
    logger.info("Setting up KeyToScalar stage with input type: " + inputType);
    // need to 'shuffle' groups across observables into
    // single observable<GroupedObservable>
    Observable<GroupedObservable<String, T>> shuffled = Groups.flattenMantisGroupsToGroupedObservables(source);
    return executeGroupsInParallel(shuffled, stage.getComputation(), context,
            stage.getKeyExpireTimeSeconds());
}
 
Example #25
Source File: OperatorGroupBy.java    From mantis with Apache License 2.0 5 votes vote down vote up
public GroupBySubscriber(
        Func1<? super T, ? extends K> keySelector,
        Func1<? super T, ? extends R> elementSelector,
        Subscriber<? super GroupedObservable<K, R>> child) {
    super();
    this.keySelector = keySelector;
    this.elementSelector = elementSelector;
    this.child = child;
}
 
Example #26
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnsubscribeViaTakeOnGroupThenTakeOnInner() {
    final AtomicInteger subscribeCounter = new AtomicInteger();
    final AtomicInteger sentEventCounter = new AtomicInteger();
    final AtomicInteger eventCounter = new AtomicInteger();

    SYNC_INFINITE_OBSERVABLE_OF_EVENT(4, subscribeCounter, sentEventCounter)
            .groupBy(new Func1<Event, Integer>() {

                @Override
                public Integer call(Event e) {
                    return e.source;
                }
            })
            // take 2 of the 4 groups
            .take(2)
            .flatMap(new Func1<GroupedObservable<Integer, Event>, Observable<String>>() {

                @Override
                public Observable<String> call(GroupedObservable<Integer, Event> eventGroupedObservable) {
                    int numToTake = 0;
                    if (eventGroupedObservable.getKey() == 1) {
                        numToTake = 10;
                    } else if (eventGroupedObservable.getKey() == 2) {
                        numToTake = 5;
                    }
                    return eventGroupedObservable
                            .take(numToTake)
                            .map(new Func1<Event, String>() {

                                @Override
                                public String call(Event event) {
                                    return "testUnsubscribe => Source: " + event.source + "  Message: " + event.message;
                                }
                            });

                }
            })
            .subscribe(new Action1<String>() {

                @Override
                public void call(String s) {
                    eventCounter.incrementAndGet();
                    System.out.println("=> " + s);
                }

            });

    assertEquals(15, eventCounter.get());
    // we should send 22 additional events that are filtered out as they are skipped while taking the 15 we want
    assertEquals(37, sentEventCounter.get());
}
 
Example #27
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testStaggeredCompletion() throws InterruptedException {
    final AtomicInteger eventCounter = new AtomicInteger();
    final CountDownLatch latch = new CountDownLatch(1);
    Observable.range(0, 100)
            .groupBy(new Func1<Integer, Integer>() {

                @Override
                public Integer call(Integer i) {
                    return i % 2;
                }
            })
            .flatMap(new Func1<GroupedObservable<Integer, Integer>, Observable<Integer>>() {

                @Override
                public Observable<Integer> call(GroupedObservable<Integer, Integer> group) {
                    if (group.getKey() == 0) {
                        return group.delay(100, TimeUnit.MILLISECONDS).map(new Func1<Integer, Integer>() {
                            @Override
                            public Integer call(Integer t) {
                                return t * 10;
                            }

                        });
                    } else {
                        return group;
                    }
                }
            })
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onCompleted() {
                    System.out.println("=> onCompleted");
                    latch.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    latch.countDown();
                }

                @Override
                public void onNext(Integer s) {
                    eventCounter.incrementAndGet();
                    System.out.println("=> " + s);
                }
            });

    if (!latch.await(3000, TimeUnit.MILLISECONDS)) {
        fail("timed out");
    }

    assertEquals(100, eventCounter.get());
}
 
Example #28
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnsubscribeViaTakeOnGroupThenMergeAndTake() {
    final AtomicInteger subscribeCounter = new AtomicInteger();
    final AtomicInteger sentEventCounter = new AtomicInteger();
    final AtomicInteger eventCounter = new AtomicInteger();

    SYNC_INFINITE_OBSERVABLE_OF_EVENT(4, subscribeCounter, sentEventCounter)
            .groupBy(new Func1<Event, Integer>() {

                @Override
                public Integer call(Event e) {
                    return e.source;
                }
            })
            // take 2 of the 4 groups
            .take(2)
            .flatMap(new Func1<GroupedObservable<Integer, Event>, Observable<String>>() {

                @Override
                public Observable<String> call(GroupedObservable<Integer, Event> eventGroupedObservable) {
                    return eventGroupedObservable
                            .map(new Func1<Event, String>() {

                                @Override
                                public String call(Event event) {
                                    return "testUnsubscribe => Source: " + event.source + "  Message: " + event.message;
                                }
                            });

                }
            })
            .take(30).subscribe(new Action1<String>() {

        @Override
        public void call(String s) {
            eventCounter.incrementAndGet();
            System.out.println("=> " + s);
        }

    });

    assertEquals(30, eventCounter.get());
    // we should send 28 additional events that are filtered out as they are in the groups we skip
    assertEquals(58, sentEventCounter.get());
}
 
Example #29
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testIgnoringGroups() {
    final AtomicInteger subscribeCounter = new AtomicInteger();
    final AtomicInteger sentEventCounter = new AtomicInteger();
    final AtomicInteger eventCounter = new AtomicInteger();

    SYNC_INFINITE_OBSERVABLE_OF_EVENT(4, subscribeCounter, sentEventCounter)
            .groupBy(new Func1<Event, Integer>() {

                @Override
                public Integer call(Event e) {
                    return e.source;
                }
            })
            .flatMap(new Func1<GroupedObservable<Integer, Event>, Observable<String>>() {

                @Override
                public Observable<String> call(GroupedObservable<Integer, Event> eventGroupedObservable) {
                    Observable<Event> eventStream = eventGroupedObservable;
                    if (eventGroupedObservable.getKey() >= 2) {
                        // filter these
                        eventStream = eventGroupedObservable.filter(new Func1<Event, Boolean>() {

                            @Override
                            public Boolean call(Event t1) {
                                return false;
                            }

                        });
                    }

                    return eventStream
                            .map(new Func1<Event, String>() {

                                @Override
                                public String call(Event event) {
                                    return "testUnsubscribe => Source: " + event.source + "  Message: " + event.message;
                                }
                            });

                }
            })
            .take(30).subscribe(new Action1<String>() {

        @Override
        public void call(String s) {
            eventCounter.incrementAndGet();
            System.out.println("=> " + s);
        }

    });

    assertEquals(30, eventCounter.get());
    // we should send 30 additional events that are filtered out as they are in the groups we skip
    assertEquals(60, sentEventCounter.get());
}
 
Example #30
Source File: OperatorGroupByTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testGroupsWithNestedObserveOn() throws InterruptedException {
    final ArrayList<String> results = new ArrayList<String>();
    Observable.create(new OnSubscribe<Integer>() {

        @Override
        public void call(Subscriber<? super Integer> sub) {
            sub.onNext(1);
            sub.onNext(2);
            sub.onNext(1);
            sub.onNext(2);
            sub.onCompleted();
        }

    }).groupBy(new Func1<Integer, Integer>() {

        @Override
        public Integer call(Integer t) {
            return t;
        }

    }).flatMap(new Func1<GroupedObservable<Integer, Integer>, Observable<String>>() {

        @Override
        public Observable<String> call(final GroupedObservable<Integer, Integer> group) {
            return group.observeOn(Schedulers.newThread()).delay(400, TimeUnit.MILLISECONDS).map(new Func1<Integer, String>() {

                @Override
                public String call(Integer t1) {
                    return "first groups: " + t1;
                }

            });
        }

    }).toBlocking().forEach(new Action1<String>() {

        @Override
        public void call(String s) {
            results.add(s);
        }

    });

    System.out.println("Results: " + results);
    assertEquals(4, results.size());
}