Java Code Examples for io.vertx.rx.java.RxHelper

The following examples show how to use io.vertx.rx.java.RxHelper. These examples are extracted from open source projects. 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 Project: vertx-rx   Source File: CoreApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduledTimer() {
  vertx.runOnContext(v -> {
    long startTime = System.currentTimeMillis();
    Context initCtx = Vertx.currentContext();
    Observable.timer(100, 100, TimeUnit.MILLISECONDS, io.vertx.rxjava.core.RxHelper.scheduler(vertx)).take(10).subscribe(new Observer<Long>() {
      public void onNext(Long value) {
        assertEquals(initCtx.getDelegate(), Vertx.currentContext().getDelegate());
      }

      public void onError(Throwable e) {
        fail("unexpected failure");
      }

      public void onCompleted() {
        long timeTaken = System.currentTimeMillis() - startTime;
        assertTrue("Was expecting to have time taken | " + timeTaken + " -  1000 | < 200", Math.abs(timeTaken - 1000) < 1000);
        testComplete();
      }
    });
  });
  await();
}
 
Example 2
Source Project: vertx-rx   Source File: CoreApiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testObserverToHandler() throws Exception {
  AtomicInteger count = new AtomicInteger();
  Observer<Long> observer = new Observer<Long>() {
    @Override
    public void onCompleted() {
      assertEquals(1, count.get());
      testComplete();
    }

    @Override
    public void onError(Throwable e) {
      fail(e.getMessage());
    }

    @Override
    public void onNext(Long l) {
      count.incrementAndGet();
    }
  };
  vertx.setTimer(1, RxHelper.toHandler(observer));
  await();
}
 
Example 3
Source Project: vertx-rx   Source File: SchedulerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribePeriodicInTask() throws Exception {
  ContextScheduler scheduler = (ContextScheduler) RxHelper.blockingScheduler(vertx);
  ContextScheduler.ContextWorker worker = scheduler.createWorker();
  CountDownLatch latch = new CountDownLatch(1);
  AtomicReference<Subscription> ref = new AtomicReference<>();
  ref.set(worker.schedulePeriodically(() -> {
    Subscription sub;
    while ((sub = ref.get()) == null) {
      Thread.yield();
    }
    sub.unsubscribe();
    latch.countDown();
  }, 10, 10, MILLISECONDS));
  awaitLatch(latch);
  waitUntil(() -> worker.countActions() == 0);
}
 
Example 4
Source Project: vertx-rx   Source File: WriteStreamSubscriberTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteStreamError() throws Exception {
  waitFor(2);
  RuntimeException expected = new RuntimeException();
  FakeWriteStream writeStream = new FakeWriteStream(vertx).failAfterWrite(expected);
  Subscriber<Integer> subscriber = RxHelper.toSubscriber(writeStream).onWriteStreamError(throwable -> {
    assertThat(throwable, is(sameInstance(expected)));
    complete();
  });
  Observable.<Integer>create(s -> s.onNext(0)).observeOn(RxHelper.scheduler(vertx))
    .doOnUnsubscribe(this::complete)
    .subscribeOn(RxHelper.scheduler(vertx))
    .subscribe(subscriber);
  await();
  assertFalse("Did not expect writeStream end method to be invoked", writeStream.endInvoked());
}
 
Example 5
Source Project: vertx-rx   Source File: AsyncResultHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRejectAdaptedFunctions3() {
  TestSubscriber<String> subscriber = new TestSubscriber<>();
  Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber::onNext, subscriber::onError, subscriber::onCompleted);
  Exception cause = new Exception();
  o.handle(Future.failedFuture(cause));
  subscriber.assertError(cause).assertEmpty();
}
 
Example 6
@Test
public void testSearchRx(TestContext testContext) throws Exception {

    final Async async = testContext.async();
    final JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("obj", new JsonObject()
                    .put("array", new JsonArray()
                            .add("1")
                            .add("2")));

    final SearchOptions searchOptions = new SearchOptions()
            .setTimeoutInMillis(1000l)
            .setSize(10)
            .setSourceIncludes(Arrays.asList("user", "message"))
            .addFieldSort("user", SortOrder.DESC)
            .addScripSort("doc['message'].value", "painless", ScriptSortOption.Type.STRING, new JsonObject().put("param1", ImmutableList.of("1", "2", "3")), SortOrder.ASC)
            .addScriptField("script_field", "doc['message'].value", "painless", new JsonObject().put("param1", ImmutableList.of("1", "2", "3")))
            .setQuery(new JsonObject().put("match_all", new JsonObject()));

    final IndexOptions indexOptions = new IndexOptions().setId(id);
    rxService.index(index, type, source, indexOptions)
            .flatMap(indexResponse -> {
                final ObservableFuture<IndexResponse> observableFuture = RxHelper.observableFuture();
                vertx.setTimer(2000l, event -> observableFuture.toHandler().handle(Future.succeededFuture(indexResponse)));
                return observableFuture;
            })
            .flatMap(indexResponse -> rxService.search(index, searchOptions))
            .subscribe(
                    searchResponse -> {
                        assertSearch(testContext, searchResponse);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example 7
@Test
public void testSearch_SuggestRx(TestContext testContext) throws Exception {

    final Async async = testContext.async();
    final JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("message_suggest", source_message);

    rxService.index(index, type, source)
            .flatMap(result -> {
                final ObservableFuture<Void> observableFuture = RxHelper.observableFuture();
                vertx.setTimer(1000, id -> observableFuture.toHandler().handle(Future.succeededFuture()));
                return observableFuture;
            })
            .flatMap(aVoid -> {
                final SearchOptions options = new SearchOptions();
                final CompletionSuggestOption completionSuggestOption = new CompletionSuggestOption()
                        .setText("v")
                        .setField("message_suggest");
                options.addSuggestion("test-suggest", completionSuggestOption);

                return rxService.search(index, options);
            })
            .subscribe(
                    searchResponse -> {
                        assertSuggest(testContext, searchResponse);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example 8
@Test
public void testDeleteByQuerySimpleRx(TestContext testContext) throws Exception {

    final Async async = testContext.async();
    final JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("obj", new JsonObject()
                    .put("array", new JsonArray()
                            .add("1")
                            .add("2")));

    final UUID documentId = UUID.randomUUID();
    final IndexOptions indexOptions = new IndexOptions().setId(documentId.toString());

    rxService.index(index, type, source, indexOptions)
            .flatMap(result -> {
                final ObservableFuture<Void> observableFuture = RxHelper.observableFuture();
                vertx.setTimer(2000, id -> observableFuture.toHandler().handle(Future.succeededFuture()));
                return observableFuture;
            })
            .flatMap(aVoid -> {
                final DeleteByQueryOptions deleteByQueryOptions = new DeleteByQueryOptions().setTimeoutInMillis(1000l);
                return rxService.deleteByQuery(index, deleteByQueryOptions.setQuery(new JsonObject().put("ids", new JsonObject().put("values", new JsonArray().add(documentId.toString())))));
            })
            .subscribe(
                    deleteByQueryResponse -> {
                        assertDeleteByQuerySimple(testContext, deleteByQueryResponse);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example 9
@Test
public void testMultiSearchRx(TestContext testContext) throws Exception {

    final Async async = testContext.async();
    final JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("obj", new JsonObject()
                    .put("array", new JsonArray()
                            .add("1")
                            .add("2")));

    final SearchOptions searchOptions = new SearchOptions()
            .setTimeoutInMillis(1000l)
            .setSize(10)
            .setSourceIncludes(Arrays.asList("user", "message"))
            .addFieldSort("user", SortOrder.DESC)
            .addScripSort("doc['message'].value", "painless", ScriptSortOption.Type.STRING, new JsonObject().put("param1", ImmutableList.of("1", "2", "3")), SortOrder.ASC)
            .addScriptField("script_field", "doc['message'].value", "painless", new JsonObject().put("param1", ImmutableList.of("1", "2", "3")))
            .setQuery(new JsonObject().put("match_all", new JsonObject()));

    final IndexOptions indexOptions = new IndexOptions().setId(id);
    rxService.index(index, type, source, indexOptions)
            .flatMap(indexResponse -> {
                final ObservableFuture<IndexResponse> observableFuture = RxHelper.observableFuture();
                vertx.setTimer(2000l, event -> observableFuture.toHandler().handle(Future.succeededFuture(indexResponse)));
                return observableFuture;
            })
            .flatMap(indexResponse -> rxService.multiSearch(ImmutableList.of(new MultiSearchQueryOptions().addIndex(index).setSearchOptions(searchOptions))))
            .subscribe(
                    multiSearchResponse -> {
                        assertMultiSearch(testContext, multiSearchResponse);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example 10
@Test
public void testDeleteRx(TestContext testContext) throws Exception {
    final Async async = testContext.async();
    final JsonObject source = new JsonObject()
            .put("user", source_user)
            .put("message", source_message)
            .put("obj", new JsonObject()
                    .put("array", new JsonArray()
                            .add("1")
                            .add("2")));

    final UUID documentId = UUID.randomUUID();
    final IndexOptions indexOptions = new IndexOptions().setId(documentId.toString());

    rxService.index(index, type, source, indexOptions)
            .flatMap(indexResponse -> {
                final ObservableFuture<Void> observableFuture = RxHelper.observableFuture();
                vertx.setTimer(2000l, event -> observableFuture.toHandler().handle(Future.succeededFuture()));
                return observableFuture;
            })
            .flatMap(indexResponse -> rxService.delete(index, type, documentId.toString(), new DeleteOptions().setRefresh(RefreshPolicy.IMMEDIATE)))
            .subscribe(
                    deleteResponse -> {
                        assertDelete(testContext, deleteResponse, documentId);
                        async.complete();
                    },
                    error -> testContext.fail(error)
            );
}
 
Example 11
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void toObservable(Vertx vertx) {
  FileSystem fileSystem = vertx.fileSystem();
  fileSystem.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Observable<Buffer> observable = RxHelper.toObservable(file);
    observable.forEach(data -> System.out.println("Read data: " + data.toString("UTF-8")));
  });
}
 
Example 12
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void observableHandler(Vertx vertx) {
  ObservableHandler<Long> observable = RxHelper.observableHandler();
  observable.subscribe(id -> {
    // Fired
  });
  vertx.setTimer(1000, observable.toHandler());
}
 
Example 13
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void handlerToSubscriber(Observable<String> observable,
                                Single<String> single,
                                Handler<AsyncResult<String>> handler1,
                                Handler<AsyncResult<String>> handler2) {
  //
  // Subscribe to an Observable
  observable.subscribe(RxHelper.toSubscriber(handler1));

  // Subscribe to a Single
  single.subscribe(RxHelper.toSubscriber(handler2));
}
 
Example 14
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void observableFuture(Vertx vertx) {
  ObservableFuture<HttpServer> observable = RxHelper.observableFuture();
  observable.subscribe(
      server -> {
        // Server is listening
      },
      failure -> {
        // Server could not start
      }
  );
  vertx.createHttpServer(new HttpServerOptions().
      setPort(1234).
      setHost("localhost")
  ).listen(observable.toHandler());
}
 
Example 15
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void observableToHandler() {
  Observer<HttpServer> observer = new Observer<HttpServer>() {
    @Override
    public void onNext(HttpServer o) {
    }
    @Override
    public void onError(Throwable e) {
    }
    @Override
    public void onCompleted() {
    }
  };
  Handler<AsyncResult<HttpServer>> handler = RxHelper.toFuture(observer);
}
 
Example 16
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void actionsToHandler() {
  Action1<HttpServer> onNext = httpServer -> {};
  Action1<Throwable> onError = httpServer -> {};
  Action0 onComplete = () -> {};

  Handler<AsyncResult<HttpServer>> handler1 = RxHelper.toFuture(onNext);
  Handler<AsyncResult<HttpServer>> handler2 = RxHelper.toFuture(onNext, onError);
  Handler<AsyncResult<HttpServer>> handler3 = RxHelper.toFuture(onNext, onError, onComplete);
}
 
Example 17
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void unmarshaller(FileSystem fileSystem) {
  fileSystem.open("/data.txt", new OpenOptions(), result -> {
    AsyncFile file = result.result();
    Observable<Buffer> observable = RxHelper.toObservable(file);
    observable.lift(RxHelper.unmarshaller(MyPojo.class)).subscribe(
        mypojo -> {
          // Process the object
        }
    );
  });
}
 
Example 18
Source Project: vertx-rx   Source File: BufferTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMapPojoFromBuffer() throws Exception {
  Observable<Buffer> stream = Observable.from(Arrays.asList(Buffer.buffer("{\"foo\":\"bar\"}")));
  Observable<SimplePojo> mapped = stream.lift(RxHelper.unmarshaller(SimplePojo.class));
  TestSubscriber<SimplePojo> sub = new TestSubscriber<>();
  subscribe(mapped, sub);
  sub.assertItem(new SimplePojo("bar"));
  sub.assertCompleted();
  sub.assertEmpty();
}
 
Example 19
Source Project: vertx-rx   Source File: BufferTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMapObjectNodeFromBuffer() throws Exception {
  Observable<Buffer> stream = Observable.from(Arrays.asList(Buffer.buffer("{\"foo\":\"bar\"}")));
  Observable<JsonNode> mapped = stream.lift(RxHelper.unmarshaller(JsonNode.class));
  TestSubscriber<JsonNode> sub = new TestSubscriber<>();
  subscribe(mapped, sub);
  sub.assertItem(new ObjectMapper().createObjectNode().put("foo", "bar"));
  sub.assertCompleted();
  sub.assertEmpty();
}
 
Example 20
Source Project: vertx-rx   Source File: BufferTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMapPojoListFromBuffer() throws Exception {
  Observable<Buffer> stream = Observable.just(Buffer.buffer("[{\"foo\":\"bar\"}]"));
  Observable<List<SimplePojo>> mapped = stream.lift(RxHelper.unmarshaller(new TypeReference<List<SimplePojo>>(){}));
  TestSubscriber<List<SimplePojo>> sub = new TestSubscriber<>();
  subscribe(mapped, sub);
  sub.assertItems(Arrays.asList(new SimplePojo("bar")));
  sub.assertCompleted();
  sub.assertEmpty();
}
 
Example 21
Source Project: vertx-rx   Source File: CoreApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testScheduledBuffer() {
  vertx.runOnContext(v -> {
    long startTime = System.currentTimeMillis();
    Context initCtx = Vertx.currentContext();
    Observable
        .timer(10, 10, TimeUnit.MILLISECONDS, io.vertx.rxjava.core.RxHelper.scheduler(vertx))
        .buffer(100, TimeUnit.MILLISECONDS, io.vertx.rxjava.core.RxHelper.scheduler(vertx))
        .take(10)
        .subscribe(new Observer<List<Long>>() {
          private int eventCount = 0;

          public void onNext(List<Long> value) {
            eventCount++;
            assertEquals(initCtx.getDelegate(), Vertx.currentContext().getDelegate());
          }

          public void onError(Throwable e) {
            fail("unexpected failure");
          }

          public void onCompleted() {
            long timeTaken = System.currentTimeMillis() - startTime;
            assertEquals(10, eventCount);
            assertTrue("Was expecting to have time taken | " + timeTaken + " -  1000 | < 200", Math.abs(timeTaken - 1000) < 1000);
            testComplete();
          }
        });
  });
  await();
}
 
Example 22
Source Project: vertx-rx   Source File: CoreApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeMap() {
  vertx.runOnContext(v -> {
    Context initCtx = Vertx.currentContext();
    EventBus eb = vertx.eventBus();
    ReadStream<String> consumer = eb.<String>localConsumer("the-address").bodyStream();
    Observer<String> observer = new Subscriber<String>() {
      boolean first = true;
      @Override
      public void onNext(String s) {
        if (first) {
          first = false;
          assertEquals(initCtx.getDelegate(), Vertx.currentContext().getDelegate());
          assertEquals("msg1msg2msg3", s);
          testComplete();
        }
      }
      @Override
      public void onError(Throwable e) {
        fail(e.getMessage());
      }
      @Override
      public void onCompleted() {
      }
    };
    Observable<String> observable = consumer.toObservable();
    observable.
        buffer(500, TimeUnit.MILLISECONDS, io.vertx.rxjava.core.RxHelper.scheduler(vertx)).
        map(samples -> samples.stream().reduce("", (a, b) -> a + b)).
        subscribe(observer);
    eb.send("the-address", "msg1");
    eb.send("the-address", "msg2");
    eb.send("the-address", "msg3");
  });
  await();
}
 
Example 23
Source Project: vertx-rx   Source File: CoreApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployVerticle() throws Exception {
  CountDownLatch deployLatch = new CountDownLatch(2);
  io.vertx.rxjava.core.RxHelper.deployVerticle(vertx, new AbstractVerticle() {
    @Override
    public void start() {
      deployLatch.countDown();
    }
  }).subscribe(resp -> {
    deployLatch.countDown();
  });
  awaitLatch(deployLatch);
}
 
Example 24
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleFutureSubscriptionSuccess() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  SingleEmitter<String> emitter = subscribeToSingle(sub);
  assertEquals(Collections.emptyList(), results);
  emitter.onSuccess("the-value-1");
  assertEquals(Collections.singletonList("the-value-1"), results);
  emitter.onSuccess("the-value-2");
  assertEquals(Collections.singletonList("the-value-1"), results);
}
 
Example 25
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleFutureSubscriptionError() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  SingleEmitter<String> emitter = subscribeToSingle(sub);
  assertEquals(Collections.emptyList(), results);
  Throwable cause = new Throwable();
  emitter.onError(cause);
  assertEquals(Collections.singletonList(cause), results);
  emitter.onSuccess("the-value");
  assertEquals(Collections.singletonList(cause), results);
}
 
Example 26
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObservableFutureSubscriptionCompletedWithNoItems() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  Emitter<String> emitter = subscribe(sub);
  assertEquals(Collections.emptyList(), results);
  emitter.onCompleted();
  assertEquals(Collections.singletonList(null), results);
  emitter.onNext("the-value-1");
  assertEquals(Collections.singletonList(null), results);
}
 
Example 27
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObservableFutureSubscriptionCompletedWithItem() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  Emitter<String> emitter = subscribe(sub);
  assertEquals(Collections.emptyList(), results);
  emitter.onNext("the-value-1");
  assertEquals(Collections.singletonList("the-value-1"), results);
  emitter.onCompleted();
  emitter.onNext("the-value-1");
  assertEquals(Collections.singletonList("the-value-1"), results);
}
 
Example 28
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObservableFutureSubscriptionCompletedWithItems() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  Emitter<String> emitter = subscribe(sub);
  assertEquals(Collections.emptyList(), results);
  emitter.onNext("the-value-1");
  assertEquals(Collections.singletonList("the-value-1"), results);
  emitter.onNext("the-value-2");
  assertEquals(Collections.singletonList("the-value-1"), results);
}
 
Example 29
Source Project: vertx-rx   Source File: SubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObservableFutureSubscriptionError() {
  List<Object> results = new ArrayList<>();
  Subscriber<String> sub = RxHelper.toSubscriber(handler(results));
  Emitter<String> emitter = subscribe(sub);
  assertEquals(Collections.emptyList(), results);
  Throwable cause = new Throwable();
  emitter.onError(cause);
  assertEquals(Collections.singletonList(cause), results);
  emitter.onNext("the-value");
  assertEquals(Collections.singletonList(cause), results);
}
 
Example 30
Source Project: vertx-rx   Source File: SchedulerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovedFromContextAfterRun() throws Exception {
  ContextScheduler scheduler = (ContextScheduler) RxHelper.blockingScheduler(vertx);
  ContextScheduler.ContextWorker worker = scheduler.createWorker();
  CountDownLatch latch = new CountDownLatch(1);
  worker.schedule(latch::countDown);
  awaitLatch(latch);
  waitUntil(() -> worker.countActions() == 0);
}