io.reactivex.Flowable Java Examples
The following examples show how to use
io.reactivex.Flowable.
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: NewSolTest.java From web3sdk with Apache License 2.0 | 6 votes |
public Flowable<TransferEventResponse> transferEventFlowable(BcosFilter filter) { return web3j.logFlowable(filter) .map( new io.reactivex.functions.Function<Log, TransferEventResponse>() { @Override public TransferEventResponse apply(Log log) { EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log); TransferEventResponse typedResponse = new TransferEventResponse(); typedResponse.log = log; typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); typedResponse.tokens = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; } }); }
Example #2
Source File: PgClientDbRepository.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Flowable<Fortune> fortunes() { return Flowable.create(sink -> pgClients.getOne().preparedQuery("SELECT * FROM fortune", ar -> { if (ar.failed()) { sink.onError(ar.cause()); return; } PgIterator resultSet = ar.result().iterator(); while (resultSet.hasNext()) { Tuple row = resultSet.next(); sink.onNext(new Fortune(row.getInteger(0), row.getString(1))); } sink.onComplete(); }), BackpressureStrategy.BUFFER); }
Example #3
Source File: PostOptionTableConnection.java From mimi-reader with Apache License 2.0 | 6 votes |
private static Flowable<Boolean> insertPostOption(String option) { PostOption postOption = new PostOption(); postOption.option = option; postOption.lastUsed = System.currentTimeMillis(); BriteDatabase db = MimiApplication.getInstance().getBriteDatabase(); BriteDatabase.Transaction transaction = db.newTransaction(); long val = 0; try { val = db.insert(PostOption.TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, postOption.toContentValues()); transaction.markSuccessful(); } catch (Exception e) { Log.e(LOG_TAG, "Error putting post options into the database", e); } finally { transaction.end(); } return Flowable.just(val > 0); }
Example #4
Source File: RetryWhenTest.java From rxjava2-extras with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testRetryWhenSpecificExceptionFails() { Exception ex = new IllegalArgumentException("boo"); TestSubscriber<Integer> ts = TestSubscriber.create(); TestScheduler scheduler = new TestScheduler(); Flowable.just(1, 2) // force error after 3 emissions .concatWith(Flowable.<Integer>error(ex)) // retry with backoff .retryWhen(RetryWhen.maxRetries(2).action(log).exponentialBackoff(1, TimeUnit.MINUTES) .scheduler(scheduler).failWhenInstanceOf(IllegalArgumentException.class).build()) // go .subscribe(ts); ts.assertValues(1, 2); ts.assertError(ex); }
Example #5
Source File: PortfolioServiceImpl.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
private void computeEvaluation(WebClient webClient, Handler<AsyncResult<Double>> resultHandler) { // We need to call the service for each company in which we own shares Flowable.fromIterable(portfolio.getShares().entrySet()) // For each, we retrieve the value .flatMapSingle(entry -> getValueForCompany(webClient, entry.getKey(), entry.getValue())) // We accumulate the results .toList() // And compute the sum .map(list -> list.stream().mapToDouble(x -> x).sum()) // We report the result or failure .subscribe((sum, err) -> { if (err != null) { resultHandler.handle(Future.failedFuture(err)); } else { resultHandler.handle(Future.succeededFuture(sum)); } }); }
Example #6
Source File: RestHelper.java From mvvm-template with GNU General Public License v3.0 | 6 votes |
/** * Create a mapper from retrofit service to {@link Resource} with rx's {@link Flowable} * To indicate current state while execute an rest api (loading, error, success with status and message if error) * @param remote from retrofit service * @param onSave will be called after success response come, to save response data into local database * @param <T> type of response * @return a {@link Flowable} instance to deal with progress showing and error handling */ public static <T> Flowable<Resource<T>> createRemoteSourceMapper(@Nullable Single<T> remote, @Nullable PlainConsumer<T> onSave) { return Flowable.create(emitter -> { new SimpleRemoteSourceMapper<T>(emitter) { @Override public Single<T> getRemote() { return remote; } @Override public void saveCallResult(T data) { if (onSave != null) { onSave.accept(data); } } }; }, BackpressureStrategy.BUFFER); }
Example #7
Source File: MultiFlattenTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testWithPublishers() { AtomicBoolean subscribed = new AtomicBoolean(); MultiAssertSubscriber<String> subscriber = Multi.createFrom().items( Flowable.just("a", "b", "c"), Flowable.just("d", "e"), Flowable.empty(), Flowable.just("f", "g") .doOnSubscribe(s -> subscribed.set(true))) .onItem().<String> disjoint() .subscribe().withSubscriber(MultiAssertSubscriber.create(4)); assertThat(subscribed).isFalse(); subscriber.assertReceived("a", "b", "c", "d"); subscriber.request(3); subscriber.assertCompletedSuccessfully(); assertThat(subscriber.items()).contains("e", "f", "g"); assertThat(subscribed).isTrue(); }
Example #8
Source File: MqttSinkTest.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testSinkUsingChannelName() throws InterruptedException { String topic = UUID.randomUUID().toString(); CountDownLatch latch = new CountDownLatch(1); AtomicInteger expected = new AtomicInteger(0); usage.consumeIntegers(topic, 10, 10, TimeUnit.SECONDS, latch::countDown, v -> expected.getAndIncrement()); Map<String, Object> config = new HashMap<>(); config.put("channel-name", topic); config.put("host", address); config.put("port", port); MqttSink sink = new MqttSink(vertx, new MqttConnectorOutgoingConfiguration(new MapBasedConfig(config))); Subscriber<? extends Message<?>> subscriber = sink.getSink().build(); Flowable.range(0, 10) .map(Message::of) .subscribe((Subscriber<? super Message<Integer>>) subscriber); assertThat(latch.await(1, TimeUnit.MINUTES)).isTrue(); await().untilAtomic(expected, is(10)); assertThat(expected).hasValue(10); }
Example #9
Source File: SplashActivity.java From NewFastFrame with Apache License 2.0 | 6 votes |
@Override protected void onResume() { super.onResume(); boolean isLogin = BaseApplication.getAppComponent().getSharedPreferences().getBoolean(ConstantUtil.LOGIN_STATUS, false); if (isLogin) { Flowable.timer(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aLong -> { LogUtil.e("该用户有缓存数据,直接跳转到主界面"); updateUserInfo(); }); } else { Flowable.timer(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aLong -> { LogUtil.e("该用户无缓存数据,直接跳转到登录界面"); LoginActivity.start(SplashActivity.this, null); finish(); }); } }
Example #10
Source File: AWSParameterStoreConfigClient.java From micronaut-aws with Apache License 2.0 | 5 votes |
private static Publisher<? extends GetParametersByPathResult> onGetParametersByPathResult(Throwable throwable) { if (throwable instanceof SdkClientException) { return Flowable.error(throwable); } else { return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable)); } }
Example #11
Source File: FirstTest.java From camelinaction2 with Apache License 2.0 | 5 votes |
@Test public void testFirst() throws Exception { LOG.info("Starting RX-Java2 Flowable first"); // use stream engine to subscribe from a timer interval that runs a continued // stream with data once per second Flowable.just("Camel", "rocks", "streams", "as", "well") // upper case the word .map(String::toUpperCase) // log the big number .doOnNext(LOG::info) // start the subscriber so it runs .subscribe(); }
Example #12
Source File: FlowableBehaviorCheckerTest.java From storio with Apache License 2.0 | 5 votes |
@Test public void shouldDenyUsingNullTestAction() { try { //noinspection ConstantConditions new FlowableBehaviorChecker<Object>() .flowable(Flowable.just(new Object())) .expectedNumberOfEmissions(1) .checkBehaviorOfFlowable(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("Please specify fields"); } }
Example #13
Source File: GitHubServiceImpl.java From Java-9-Spring-Webflux with Apache License 2.0 | 5 votes |
@Override public Flowable<CommittedFile> getCommittedFilesByUrl(String url) { return Flowable.create(emitter -> { SingleCommit commit = gitHbubRepos.getSingleCommitByUrl(url); log.info(commit.toString()); commit.getFiles().forEach(files -> { log.info(files.toString()); emitter.onNext(files); }); emitter.onComplete(); }, BackpressureStrategy.BUFFER); }
Example #14
Source File: IgniteCacheEventStreamerRx.java From spring-boot-akka-event-sourcing-starter with Apache License 2.0 | 5 votes |
/** * start and execute the streamer flow */ @SuppressWarnings("unchecked") public final void execute() { log.info("starting the stream for the ignite source/sink flow"); if (igniteCacheSourceTask.isStopped()) throw new IllegalStateException("Ignite source task is not yet started"); if (igniteCacheSinkTask.isStopped()) throw new IllegalStateException("Ignite sink task is not yet started"); //noinspection unchecked Flowable.fromCallable(igniteCacheSourceTask::poll) .repeatWhen(flowable -> flowable.delay(periodicInterval, TimeUnit.MILLISECONDS)) .retry(retryTimes, retryPredicate) .doOnError(throwable -> streamReport.addErrorMsg(throwable.getMessage())) .doOnNext(igniteCacheSinkTask::put) .doOnError(throwable -> streamReport.addErrorMsg(throwable.getMessage())) .doOnNext(data -> { if (null != data && !data.isEmpty() && atomicInteger.addAndGet(data.size()) % flushBufferSize == 0) { igniteCacheSinkTask.flush(); } }) .retry(retryTimes, retryPredicate) .doOnError(throwable -> streamReport.addErrorMsg(throwable.getMessage())) .doFinally(() -> { log.info("cleaning and stopping ignite tasks from the stream"); if (log.isDebugEnabled()) { log.debug("final execution report: error messages : {}, Total streamed record number : {}", streamReport.getErrorMsgs().toArray(), streamReport.getAddedRecords()); } igniteCacheSinkTask.stop(); igniteCacheSourceTask.stop(); }) .subscribe(onNextAction, onErrorAction); }
Example #15
Source File: PermissionService.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private Single<Map<Membership, Map<Permission, Set<Acl>>>> findMembershipPermissions(User user, Stream<Map.Entry<ReferenceType, String>> referenceStream) { return groupService.findByMember(user.getId()) .flattenAsFlowable(groups -> groups) .map(Group::getId) .toList() .flatMap(userGroupIds -> { MembershipCriteria criteria = new MembershipCriteria(); criteria.setUserId(user.getId()); criteria.setGroupIds(userGroupIds.isEmpty() ? null : userGroupIds); criteria.setLogicalOR(true); // Get all user and group memberships. return Flowable.merge(referenceStream.map(p -> membershipService.findByCriteria(p.getKey(), p.getValue(), criteria)).collect(Collectors.toList())) .toList() .flatMap(allMemberships -> { if (allMemberships.isEmpty()) { return Single.just(Collections.emptyMap()); } // Get all roles. return roleService.findByIdIn(allMemberships.stream().map(Membership::getRoleId).collect(Collectors.toList())) .map(allRoles -> permissionsPerMembership(allMemberships, allRoles)); }); }); }
Example #16
Source File: GetOperationTest.java From storio with Apache License 2.0 | 5 votes |
@Test public void getExistedObjectExecuteAsFlowable() { final TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI, BackpressureStrategy.MISSING) .take(1) .subscribe(changesTestSubscriber); TestItem expectedItem = TestItem.create(null, "value"); contentResolver.insert(TestItem.CONTENT_URI, expectedItem.toContentValues()); contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value1").toContentValues()); contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value2").toContentValues()); Flowable<Optional<TestItem>> testItemFlowable = storIOContentResolver .get() .object(TestItem.class) .withQuery(Query.builder() .uri(TestItem.CONTENT_URI) .where(TestItem.COLUMN_VALUE + "=?") .whereArgs("value") .build()) .prepare() .asRxFlowable(BackpressureStrategy.MISSING) .take(1); TestSubscriber<Optional<TestItem>> testSubscriber = new TestSubscriber<Optional<TestItem>>(); testItemFlowable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(5, SECONDS); testSubscriber.assertNoErrors(); List<Optional<TestItem>> emmitedItems = testSubscriber.values(); assertThat(emmitedItems.size()).isEqualTo(1); assertThat(expectedItem.equalsWithoutId(emmitedItems.get(0).get())).isTrue(); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValue(Changes.newInstance(TestItem.CONTENT_URI)); }
Example #17
Source File: PreparedGetCursorTest.java From storio with Apache License 2.0 | 5 votes |
@Test public void shouldWrapExceptionIntoStorIOExceptionForFlowable() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); when(storIOSQLite.observeChanges(any(BackpressureStrategy.class))).thenReturn(Flowable.<Changes>empty()); //noinspection unchecked final GetResolver<Cursor> getResolver = mock(GetResolver.class); when(getResolver.performGet(eq(storIOSQLite), any(Query.class))) .thenThrow(new IllegalStateException("test exception")); final TestSubscriber<Cursor> testSubscriber = new TestSubscriber<Cursor>(); new PreparedGetCursor.Builder(storIOSQLite) .withQuery(Query.builder().table("test_table").observesTags("test_tag").build()) .withGetResolver(getResolver) .prepare() .asRxFlowable(LATEST) .subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(60, SECONDS); testSubscriber.assertError(StorIOException.class); StorIOException storIOException = (StorIOException) testSubscriber.errors().get(0); IllegalStateException cause = (IllegalStateException) storIOException.getCause(); assertThat(cause).hasMessage("test exception"); testSubscriber.dispose(); }
Example #18
Source File: BeanProducingAProcessorBuilderOfMessages.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming("count") @Outgoing("sink") public ProcessorBuilder<Message<Integer>, Message<String>> process() { return ReactiveStreams.<Message<Integer>> builder() .map(Message::getPayload) .map(i -> i + 1) .flatMapRsPublisher(i -> Flowable.just(i, i)) .map(i -> Integer.toString(i)) .map(Message::of); }
Example #19
Source File: TransformersTest.java From rxjava2-extras with Apache License 2.0 | 5 votes |
@Test public void testStatisticsOnEmptyStream() { Flowable<Integer> nums = Flowable.empty(); Statistics s = nums.compose(Transformers.<Integer>collectStats()).blockingLast(); assertEquals(0, s.count()); assertEquals(0, s.sum(), 0.0001); assertTrue(Double.isNaN(s.mean())); assertTrue(Double.isNaN(s.sd())); }
Example #20
Source File: HttpEntityArgumentResolverTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void supports() throws Exception { testSupports(this.testMethod.arg(httpEntityType(String.class))); testSupports(this.testMethod.arg(httpEntityType(Mono.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(Single.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(io.reactivex.Single.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(Maybe.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(CompletableFuture.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(Flux.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(Observable.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(io.reactivex.Observable.class, String.class))); testSupports(this.testMethod.arg(httpEntityType(Flowable.class, String.class))); testSupports(this.testMethod.arg(forClassWithGenerics(RequestEntity.class, String.class))); }
Example #21
Source File: TimeLimiterTransformerPublisherTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void timeout() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ZERO)); TestSubscriber<Long> subscriber = Flowable.interval(1, TimeUnit.MINUTES) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); subscriber.assertError(TimeoutException.class); then(timeLimiter).should() .onError(any(TimeoutException.class)); }
Example #22
Source File: GitHubServiceImpl.java From Java-programming-methodology-Rxjava-articles with Apache License 2.0 | 5 votes |
@Override public Flowable<CommittedFile> getCommittedFilesByUrl(String url) { return Flowable.create(emitter -> { SingleCommit commit = gitHbubRepos.getSingleCommitByUrl(url); log.info(commit.toString()); commit.getFiles().forEach(files -> { log.info(files.toString()); emitter.onNext(files); }); emitter.onComplete(); }, BackpressureStrategy.BUFFER); }
Example #23
Source File: ErrorAndEmptyAdapterHelper.java From MultiTypeRecyclerViewAdapter with Apache License 2.0 | 5 votes |
@SuppressLint("CheckResult") @Override protected void startRefresh(HandleBase<StickyItem> refreshData) { Flowable.just(refreshData) .onBackpressureDrop() .observeOn(Schedulers.computation()) .map(handleBase -> handleRefresh(handleBase.getNewData(), handleBase.getNewHeader(), handleBase.getNewFooter(), handleBase.getLevel(), handleBase.getRefreshType())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleResult); }
Example #24
Source File: FlowableRateLimiterTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldEmitSingleEventWithSinglePermit() { given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos()); Flowable.just(1) .compose(RateLimiterOperator.of(rateLimiter)) .test() .assertResult(1); }
Example #25
Source File: JsonRpc2_0Rx.java From web3j with Apache License 2.0 | 5 votes |
public Flowable<EthBlock> blockFlowable(boolean fullTransactionObjects, long pollingInterval) { return ethBlockHashFlowable(pollingInterval) .flatMap( blockHash -> web3j.ethGetBlockByHash(blockHash, fullTransactionObjects) .flowable()); }
Example #26
Source File: CurrentTraceContextAssemblyTrackingMatrixTest.java From brave with Apache License 2.0 | 5 votes |
@Test public void callable_flowable_conditional_assembleNoScope_subscribeInScope() { Flowable<Integer> source = callableFlowable(subscribeContext) .filter(lessThanThreeInSubscribeContext) .doOnNext(e -> assertInSubscribeContext()) .doOnComplete(this::assertInSubscribeContext); Flowable<Integer> errorSource = callableFlowable(subscribeContext, new IllegalStateException()) .filter(lessThanThreeInSubscribeContext) .doOnError(t -> assertInSubscribeContext()) .doOnComplete(this::assertInSubscribeContext); subscribeInDifferentContext(source.toObservable(), errorSource.toObservable()).assertResult(1); }
Example #27
Source File: MaybeUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenEmitsNoValue_thenSignalsCompletionAndNoValueObserved() { Maybe<Integer> maybe = Flowable.just(1, 2, 3, 4, 5) .skip(5) .firstElement(); maybe.test() .assertComplete() .assertNoValues(); }
Example #28
Source File: FixedTimeStreamWindowTest.java From pentaho-kettle with Apache License 2.0 | 5 votes |
@Test public void supportsPostProcessing() throws KettleException { RowMetaInterface rowMeta = new RowMeta(); rowMeta.addValueMeta( new ValueMetaString( "field" ) ); Result mockResult = new Result(); mockResult.setRows( Arrays.asList( new RowMetaAndData( rowMeta, "queen" ), new RowMetaAndData( rowMeta, "king" ) ) ); when( subtransExecutor.execute( any() ) ).thenReturn( Optional.of( mockResult ) ); when( subtransExecutor.getPrefetchCount() ).thenReturn( 10 ); AtomicInteger count = new AtomicInteger(); FixedTimeStreamWindow<List> window = new FixedTimeStreamWindow<>( subtransExecutor, rowMeta, 0, 2, 1, ( p ) -> count.set( p.getKey().get( 0 ).size() ) ); window.buffer( Flowable.fromIterable( singletonList( asList( "v1", "v2" ) ) ) ) .forEach( result -> assertEquals( mockResult, result ) ); assertEquals( 2, count.get() ); }
Example #29
Source File: RxJavaUtils.java From Collection-Android with MIT License | 5 votes |
/** * 执行Rx通用任务 (IO线程中执行耗时操作 执行完成调用UI线程中的方法) * * @param rxTask 执行任务 * @param errorConsumer 出错的处理 * @param <T> * @return */ public static <T, R> Disposable executeAsyncTask(@NonNull RxAsyncTask<T, R> rxTask, @NonNull Consumer<Throwable> errorConsumer) { RxTaskOnSubscribe<RxAsyncTask<T, R>> onSubscribe = getRxAsyncTaskOnSubscribe(rxTask); return Flowable.create(onSubscribe, BackpressureStrategy.LATEST) .compose(RxSchedulerUtils.<RxAsyncTask<T, R>>_io_main_f()) .subscribe(new Consumer<RxAsyncTask<T, R>>() { @Override public void accept(RxAsyncTask<T, R> rxAsyncTask) throws Exception { rxAsyncTask.doInUIThread(rxAsyncTask.getOutData()); //在UI线程工作 } }, errorConsumer); }
Example #30
Source File: FlowableOnBackpressureBufferToFileTest.java From rxjava2-extras with Apache License 2.0 | 5 votes |
@Test public void testEmpty() { Flowable.<Integer>empty() // .compose(onBackpressureBufferToFile() // .<Integer>serializerJavaIO()) .test() // .awaitDone(5L, TimeUnit.SECONDS) // .assertNoValues() // .assertComplete(); // }