private void insertAndFind() { // Documents to insert Observable<JsonObject> documents = Observable.just( new JsonObject().put("username", "temporalfox").put("firstname", "Julien").put("password", "bilto"), new JsonObject().put("username", "purplefox").put("firstname", "Tim").put("password", "wibble") ); mongo.rxCreateCollection("users").flatMapObservable(v -> { // After collection is created we insert each document return documents.flatMap(doc -> mongo.rxInsert("users", doc).toObservable()); }).doOnNext(id -> { System.out.println("Inserted document " + id); }).last().toSingle().flatMap(id -> { // Everything has been inserted now we can query mongo System.out.println("Insertions done"); return mongo.rxFind("users", new JsonObject()); }).subscribe(results -> { System.out.println("Results " + results); }, error -> { System.out.println("Err"); error.printStackTrace(); }); } }
@Override public void start() throws Exception { JsonObject config = new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true") .put("driver_class", "org.hsqldb.jdbcDriver"); JDBCClient jdbc = JDBCClient.createShared(vertx, config); jdbc .rxGetConnection() // Connect to the database .flatMapObservable(conn -> { // With the connection... return conn.rxUpdate("CREATE TABLE test(col VARCHAR(20))") // ...create test table .flatMap(result -> conn.rxUpdate("INSERT INTO test (col) VALUES ('val1')")) // ...insert a row .flatMap(result -> conn.rxUpdate("INSERT INTO test (col) VALUES ('val2')")) // ...another one .flatMap(result -> conn.rxQueryStream("SELECT * FROM test")) // ...get values stream .flatMapObservable(sqlRowStream -> { return sqlRowStream.toObservable() // Transform the stream into an Observable... .doOnTerminate(conn::close); // ...and close the connection when the stream is fully read or an error occurs }); }).subscribe(row -> System.out.println("Row : " + row.encode())); } }
/** * Generates a {@link Observable} from {@link SQLConnection} operations. * * @param client the {@link SQLClient} * @param sourceSupplier a user-provided function returning a {@link Observable} generated by interacting with the given {@link SQLConnection} * @param <T> the type of the items emitted by the {@link Observable} * @return an {@link Observable} generated from {@link SQLConnection} operations */ public static <T> Observable<T> usingConnectionObservable(SQLClient client, Function<SQLConnection, Observable<T>> sourceSupplier) { return client.rxGetConnection().flatMapObservable(conn -> { return sourceSupplier.apply(conn).doAfterTerminate(conn::close); }); }
/** * Generates a {@link Observable} from {@link SQLConnection} operations. * * @param client the {@link SQLClient} * @param sourceSupplier a user-provided function returning a {@link Observable} generated by interacting with the given {@link SQLConnection} * @param <T> the type of the items emitted by the {@link Observable} * @return an {@link Observable} generated from {@link SQLConnection} operations */ public static <T> Observable<T> usingConnectionObservable(SQLClient client, Function<SQLConnection, Observable<T>> sourceSupplier) { return client.rxGetConnection().flatMapObservable(conn -> { return sourceSupplier.apply(conn).doAfterTerminate(conn::close); }); }
@Override public Observable<CartEvent> streamByUser(String userId) { JsonArray params = new JsonArray().add(userId).add(userId); return client.rxGetConnection() .flatMapObservable(conn -> conn.rxQueryWithParams(STREAM_STATEMENT, params) .map(ResultSet::getRows) .flatMapObservable(Observable::from) .map(this::wrapCartEvent) .doOnTerminate(conn::close) ); }
/** * Initialize the given merger. Perform a search using the given search string * and pass all chunk metadata retrieved to the merger. * @param merger the merger to initialize * @param data data to use for the initialization * @return a Completable that will complete when the merger has been * initialized with all results */ private Completable initializeMerger(Merger<ChunkMeta> merger, Single<StoreCursor> data) { return data .map(RxStoreCursor::new) .flatMapObservable(RxStoreCursor::toObservable) .map(Pair::getLeft) .flatMapCompletable(merger::init) .toCompletable(); }
/** * Discover all published services by name * @param name the service name * @param discovery the service discovery that should be used to discover the * services * @param vertx the Vert.x instance * @return all services published under the given the name * @see #publishOnce(Record, ServiceDiscovery, Vertx) */ static Observable<Service> discover(String name, ServiceDiscovery discovery, Vertx vertx) { return discovery.rxGetRecords(r -> r.getName().equals(name)) .flatMapObservable(Observable::from) .map(record -> { String endpoint = record.getLocation().getString(Record.ENDPOINT); Service s = new DefaultService(name, endpoint, record.getRegistration(), vertx); return s; }); }
private void loadLists() { // Load the lists Observable<List<TraktTvList>> listsObservable = mTokenManager /* Grab a valid access token (automatically refreshes the token if it is expired) */ .getValidAccessToken() /* Load lists */ .flatMapObservable(authorizationHeader -> TraktTvApiFactory.newApiService().getLists(authorizationHeader)); // Bind to lifecycle listsObservable .compose(bindToLifecycle()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(lists -> { if (lists == null || lists.isEmpty()) { handleEmptyList(); } else { handleSuccess(lists); } }, this::handleError); }
.flatMapObservable(new Func1<List<AppInfo>, Observable<AppInfo>>() { @Override public Observable<AppInfo> call(List<AppInfo> appInfos) {
void updateBlackWhitelistInternal() { DbUtil.getPerAppListApps(this).flatMapObservable(new Func1<List<AppInfo>, Observable<AppInfo>>() { @Override public Observable<AppInfo> call(List<AppInfo> appInfos) { return Observable.from(appInfos); } }).map(new Func1<AppInfo, String>() { @Override public String call(AppInfo appInfo) { return appInfo.packageName; } }).toList().toSingle() .subscribe(new SingleSubscriber<List<String>>() { @Override public void onError(Throwable e) { } @Override public void onSuccess(List<String> strings) { mFilterList = strings; mBlacklistMode = PrefUtils.isBlacklistMode(MainAccessibilityService.this); } }); }
/** * Returns sorted list of AppInfos. * <p/> * AppInfo's drawable and id are null */ public static Single<List<AppInfo>> getInstalledApps(final Context context) { return Single.create(new Single.OnSubscribe<List<ApplicationInfo>>() { @Override public void call(SingleSubscriber<? super List<ApplicationInfo>> singleSubscriber) { singleSubscriber.onSuccess(context.getPackageManager().getInstalledApplications(0)); } }).subscribeOn(Schedulers.io()) .flatMapObservable(new Func1<List<ApplicationInfo>, Observable<ApplicationInfo>>() { @Override public Observable<ApplicationInfo> call(List<ApplicationInfo> appInfos) { return Observable.from(appInfos); } }) .map(new Func1<ApplicationInfo, AppInfo>() { @Override public AppInfo call(ApplicationInfo applicationInfo) { AppInfo appInfo = new AppInfo(); appInfo.packageName = applicationInfo.packageName; appInfo.name = applicationInfo.loadLabel(context.getPackageManager()).toString(); return appInfo; } }) .toSortedList().toSingle(); }
protected Observable<String> uniqueNames(SQLConnection conn) { return conn.rxQuery(UNIQUE_NAMES_SQL) .flatMapObservable(resultSet -> Observable.from(resultSet.getResults())) .map(row -> row.getString(0)); }
@Test public void test() { getList() .subscribeOn(Schedulers.io()) .flatMapObservable(list -> Observable.from(list)) .flatMap(each -> getSubdetails(each)) .subscribe(new Subscriber<Boolean>() { @Override public void onNext(Boolean t) { } @Override public void onError(Throwable error) { } @Override public void onCompleted() { } }); } }
protected void assertTableContainsInitDataOnly() throws Exception { client.rxGetConnection().flatMapObservable(conn -> { return uniqueNames(conn).doAfterTerminate(conn::close); }).test() .awaitTerminalEvent() .assertCompleted() .assertValues(NAMES.stream().sorted().distinct().toArray(String[]::new)); }
/** * Get all values for the specified attribute * @param search the search query * @param path the path * @param attribute the name of the attribute * @param response the http response */ private void getAttributeValues(String search, String path, String attribute, HttpServerResponse response) { final Boolean[] first = {true}; response.setChunked(true); response.write("["); store.rxGetAttributeValues(search, path, attribute) .flatMapObservable(x -> new RxAsyncCursor<>(x).toObservable()) .subscribe( x -> { if (first[0]) { first[0] = false; } else { response.write(","); } response.write("\"" + StringEscapeUtils.escapeJson(x) + "\""); }, err -> fail(response, err), () -> response .write("]") .setStatusCode(200) .end()); }
/** * Get all values for the specified property * @param search the search query * @param path the path * @param property the name of the property * @param response the http response */ private void getPropertyValues(String search, String path, String property, HttpServerResponse response) { final Boolean[] first = {true}; response.setChunked(true); response.write("["); store.rxGetPropertyValues(search, path, property) .flatMapObservable(x -> new RxAsyncCursor<>(x).toObservable()) .subscribe( x -> { if (first[0]) { first[0] = false; } else { response.write(","); } response.write("\"" + StringEscapeUtils.escapeJson(x) + "\""); }, err -> fail(response, err), () -> response .write("]") .setStatusCode(200) .end()); }
@Test public void testHttpClientConnectionFailureFlatMap() { HttpClient client = vertx.createHttpClient(new HttpClientOptions()); Single<HttpClientResponse> req = client.rxGetNow(9998, "255.255.255.255", "/the_uri"); req.flatMapObservable(HttpClientResponse::toObservable).forEach( buffer -> fail(), err -> testComplete(), this::fail); await(); }
private Observable<String> inTransaction(Exception e) throws Exception { return client.rxGetConnection().flatMapObservable(conn -> { return rxInsertExtraFolks(conn) .andThen(uniqueNames(conn)) .compose(upstream -> e == null ? upstream : upstream.concatWith(Observable.error(e))) .compose(SQLClientHelper.txObservableTransformer(conn)) .concatWith(rxAssertAutoCommit(conn).toObservable()) .doAfterTerminate(conn::close); }); } }
@Test public void testHttpClientFlatMapUnmarshallPojo() { HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> { req.response().setChunked(true).end("{\"foo\":\"bar\"}"); }); server.listen(ar -> { HttpClient client = vertx.createHttpClient(new HttpClientOptions()); Single<HttpClientResponse> req = client.rxGetNow(8080, "localhost", "/the_uri"); ArrayList<SimplePojo> objects = new ArrayList<>(); req.flatMapObservable(HttpClientResponse::toObservable). lift(io.vertx.rxjava.core.RxHelper.unmarshaller(SimplePojo.class)). forEach( objects::add, err -> fail(), () -> { server.close(); assertEquals(Arrays.asList(new SimplePojo("bar")), objects); testComplete(); }); }); await(); }
@Test public void testHttpClientFlatMap() { HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> { req.response().setChunked(true).end("some_content"); }); server.listen(ar -> { HttpClient client = vertx.createHttpClient(new HttpClientOptions()); Single<HttpClientResponse> req = client.rxGetNow(8080, "localhost", "/the_uri"); Buffer content = Buffer.buffer(); req.flatMapObservable(HttpClientResponse::toObservable).forEach( content::appendBuffer, err -> fail(), () -> { server.close(); assertEquals("some_content", content.toString("UTF-8")); testComplete(); }); }); await(); }