com.github.davidmoten.rx.Functions Java Examples

The following examples show how to use com.github.davidmoten.rx.Functions. 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: RetryWhenTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryWhenSpecificExceptionAllowedUsePredicateReturnsFalse() {
    Exception ex = new IllegalArgumentException("boo");
    TestSubscriber<Integer> ts = TestSubscriber.create();
    TestScheduler scheduler = new TestScheduler();
    Func1<Throwable, Boolean> predicate = Functions.alwaysFalse();
    Observable.just(1, 2)
            // force error after 3 emissions
            .concatWith(Observable.<Integer> error(ex))
            // retry with backoff
            .retryWhen(
                    RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES)
                            .scheduler(scheduler).retryIf(predicate).build())
            // go
            .subscribe(ts);
    ts.assertValues(1, 2);
    ts.assertError(ex);
}
 
Example #2
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testBackpressure() {
    TestSubscriber<Integer> ts = TestSubscriber.create(1);
    Observable.
            //
            range(1, 1000)
            // use toOperator
            .lift(toOperator(Functions.<Observable<Integer>> identity()))
            // block and get result
            .subscribe(ts);
    // make sure only one value has arrived
    ts.assertValueCount(1);
    ts.requestMore(2);
    ts.assertValueCount(3);
    ts.unsubscribe();
}
 
Example #3
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeFromSynchronousSource() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    PublishSubject<Integer> subject = PublishSubject.create();
    subject
            // detect unsubscribe
            .doOnUnsubscribe(countDown(latch))
            // use toOperator
            .lift(toOperator(Functions.<Observable<Integer>> identity()))
            // get first only
            .take(1)
            // subscribe and ignore events
            .subscribe();
    subject.onNext(1);
    // should have unsubscribed because of take(1)
    assertTrue(latch.await(AWAIT_SECONDS, TimeUnit.SECONDS));
}
 
Example #4
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeFromAsynchronousSource() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Observable
            // every 100ms
            .interval(100, TimeUnit.MILLISECONDS)
            // detect unsubscribe
            .doOnUnsubscribe(countDown(latch))
            // use toOperator
            .lift(toOperator(Functions.<Observable<Long>> identity())).take(1).first()
            // block and get result
            .toBlocking().single();
    // wait for expected unsubscription
    assertTrue(latch.await(AWAIT_SECONDS, TimeUnit.SECONDS));

}
 
Example #5
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testForCompletionWithinStateMachine() {
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Subscriber<Integer>, Integer> transition = new Func3<Integer, Integer, Subscriber<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Subscriber<Integer> subscriber) {
            subscriber.onNext(123);
            // complete from within transition
            subscriber.onCompleted();
            return 1;
        }

    };
    Func2<? super Integer, ? super Subscriber<Integer>, Boolean> completion = Functions
            .alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    final AtomicInteger count = new AtomicInteger(0);
    Observable.just(1, 2, 3).doOnNext(Actions.increment1(count)).compose(transformer)
            .subscribe(ts);
    ts.assertValues(123);
    ts.assertCompleted();
    assertEquals(1, count.get());
}
 
Example #6
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscriptionFromTransition() {
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Subscriber<Integer>, Integer> transition = new Func3<Integer, Integer, Subscriber<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Subscriber<Integer> subscriber) {
            subscriber.onNext(123);
            subscriber.unsubscribe();
            return 1;
        }

    };
    Func2<Integer, Observer<Integer>, Boolean> completion = Functions.alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    Observable.just(1, 1, 1).repeat().compose(transformer).subscribe(ts);
    ts.assertValue(123);
    ts.assertCompleted();
    ts.assertUnsubscribed();
}
 
Example #7
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testStateTransitionThrowsError() {
    final RuntimeException ex = new RuntimeException("boo");
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Observer<Integer>, Integer> transition = new Func3<Integer, Integer, Observer<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Observer<Integer> observer) {
            throw ex;
        }

    };
    Func2<Integer, Observer<Integer>, Boolean> completion = Functions.alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    Observable.just(1, 1, 1).compose(transformer).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertError(ex);
}
 
Example #8
Source File: ObservableServerSocket.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
private static Observable<Observable<byte[]>> createServerSocketObservable(
        ServerSocket serverSocket, final long timeoutMs, final int bufferSize,
        final Action0 preAcceptAction, final Func1<? super Socket, Boolean> acceptSocket) {
    return Observable.create( //
            SyncOnSubscribe.<ServerSocket, Observable<byte[]>> createSingleState( //
                    Functions.constant0(serverSocket), //
                    new Action2<ServerSocket, Observer<? super Observable<byte[]>>>() {

                        @Override
                        public void call(ServerSocket ss,
                                Observer<? super Observable<byte[]>> observer) {
                            acceptConnection(timeoutMs, bufferSize, ss, observer,
                                    preAcceptAction, acceptSocket);
                        }
                    }));
}
 
Example #9
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testCombinerFunctionBThrowsResultsInErrorEmissionSwitched() {
    Observable<Integer> a = Observable.just(2, 1);
    Observable<Integer> b = Observable.just(1, 2);
    Obs.match(a, b, Functions.identity(), Functions.identity(),
            Functions.<Integer, Integer, Integer> throwing2())
            .to(TestingHelper.<Integer> test()).assertNoValues()
            .assertError(Functions.ThrowingException.class);
}
 
Example #10
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlesNulls() {
    Observable<Integer> a = Observable.just(null, null);
    Observable<Integer> b = Observable.just(null, null);
    Obs.match(a, b, Functions.constant(1), Functions.constant(1), COMBINER)
            .to(TestingHelper.<Integer> test()) //
            .assertValues(null, null) //
            .assertCompleted();
}
 
Example #11
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testCombinerFunctionBThrowsResultsInErrorEmission() {
    Observable<Integer> a = Observable.just(1, 2);
    Observable<Integer> b = Observable.just(2, 1);
    Obs.match(a, b, Functions.identity(), Functions.identity(),
            Functions.<Integer, Integer, Integer> throwing2())
            .to(TestingHelper.<Integer> test()) //
            .assertNoValues() //
            .assertError(Functions.ThrowingException.class);
}
 
Example #12
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyFunctionBThrowsResultsInErrorEmission() {
    Observable<Integer> a = Observable.just(1);
    Observable<Integer> b = Observable.just(1);
    Obs.match(a, b, Functions.identity(), Functions.throwing(), COMBINER)
            .to(TestingHelper.<Integer> test()) //
            .assertNoValues() //
            .assertError(Functions.ThrowingException.class);
}
 
Example #13
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeyFunctionAThrowsResultsInErrorEmission() {
    Observable<Integer> a = Observable.just(1);
    Observable<Integer> b = Observable.just(1);
    Obs.match(a, b, Functions.throwing(), Functions.identity(), COMBINER)
            .to(TestingHelper.<Integer> test()).assertNoValues()
            .assertError(Functions.ThrowingException.class);
}
 
Example #14
Source File: ObservableServerSocketTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptSocketRejectsAlways()
        throws UnknownHostException, IOException, InterruptedException {
    reset();
    TestSubscriber<Object> ts = TestSubscriber.create();
    try {
        int bufferSize = 4;
        AtomicInteger port = new AtomicInteger();
        IO.serverSocketAutoAllocatePort(Actions.setAtomic(port)) //
                .readTimeoutMs(10000) //
                .acceptTimeoutMs(200) //
                .bufferSize(bufferSize) //
                .acceptSocketIf(Functions.alwaysFalse()) //
                .create() //
                .subscribeOn(scheduler) //
                .subscribe(ts);
        Thread.sleep(300);
        Socket socket = new Socket("localhost", port.get());
        OutputStream out = socket.getOutputStream();
        out.write("12345678901234567890".getBytes());
        out.close();
        socket.close();
        Thread.sleep(1000);
        ts.assertNoValues();
    } finally {
        // will close server socket
        ts.unsubscribe();
    }
}
 
Example #15
Source File: OperatorFromTransformerTest.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleNonSimultaeousSubscriptions() {
    Observable<Integer> sequence = Observable.range(1, 3)
            .lift(toOperator(Functions.<Observable<Integer>> identity()));
    assertEquals(asList(1, 2, 3), sequence.toList().toBlocking().single());
    assertEquals(asList(1, 2, 3), sequence.toList().toBlocking().single());
}
 
Example #16
Source File: Database.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private static <T> Observable<T> beginTransactionOnNext(final Database db,
        Observable<T> source) {
    return source.concatMap(new Func1<T, Observable<T>>() {
        @Override
        public Observable<T> call(T t) {
            return db.beginTransaction().map(Functions.constant(t));
        }
    });
}
 
Example #17
Source File: Database.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an {@link Observable} that is the result of running a sequence of
 * update commands (insert/update/delete, ddl) read from the given
 * {@link Observable} sequence.
 * 
 * @param commands
 * @return
 */
public Observable<Integer> run(Observable<String> commands) {
    return commands.reduce(Observable.<Integer> empty(),
            new Func2<Observable<Integer>, String, Observable<Integer>>() {
                @Override
                public Observable<Integer> call(Observable<Integer> dep, String command) {
                    return update(command).dependsOn(dep).count();
                }
            }).flatMap(Functions.<Observable<Integer>> identity());
}
 
Example #18
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testNegativeArgumentThrowsIAE() {
    Observable<Integer> a = Observable.just(1);
    Observable<Integer> b = Observable.just(1);
    Obs.match(a, b, Functions.identity(), Functions.identity(), COMBINER, -1);
}
 
Example #19
Source File: OnSubscribeMatchTest.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
private static Observable<Integer> matchThem(Observable<Integer> a, Observable<Integer> b) {
    return a.compose(
            Transformers.matchWith(b, Functions.identity(), Functions.identity(), COMBINER));
}
 
Example #20
Source File: Database.java    From rxjava-jdbc with Apache License 2.0 2 votes vote down vote up
/**
 * Starts a transaction. Until commit() or rollback() is called on the
 * source this will set the query context for all created queries to be a
 * single threaded executor with one (new) connection.
 * 
 * @param dependency
 * @return
 */
public Observable<Boolean> beginTransaction(Observable<?> dependency) {
    return update("begin").dependsOn(dependency).count().map(Functions.constant(true));
}