本文整理汇总了Java中io.reactivex.Single.subscribe方法的典型用法代码示例。如果您正苦于以下问题:Java Single.subscribe方法的具体用法?Java Single.subscribe怎么用?Java Single.subscribe使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类io.reactivex.Single
的用法示例。
在下文中一共展示了Single.subscribe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: single_ReturnsSharedSingle
import io.reactivex.Single; //导入方法依赖的package包/类
@Test
public void single_ReturnsSharedSingle() {
// Given
final DiffRequest spyRequest = spy(mDiffRequest);
// When
final Single<RxDiffResult> single = DiffRequestManager.single(spyRequest);
// Then
for (int i = 0; i < 5; ++i) {
final TestObserver<RxDiffResult> testObserver = new TestObserver<>();
single.subscribe(testObserver);
testObserver.awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
testObserver.assertValue(new Predicate<RxDiffResult>() {
@Override
public boolean test(@NonNull RxDiffResult rxDiffResult) throws Exception {
return rxDiffResult.getTag().equals(TEST_TAG);
}
});
}
then(spyRequest).should(times(1)).isDetectingMoves();
}
示例2: oneToMany
import io.reactivex.Single; //导入方法依赖的package包/类
/**
* Implements a unary -> stream call as {@link Single} -> {@link Flowable}, where the server responds with a
* stream of messages.
*/
public static <TRequest, TResponse> Flowable<TResponse> oneToMany(
Single<TRequest> rxRequest,
final BiConsumer<TRequest, StreamObserver<TResponse>> delegate) {
try {
final RxConsumerStreamObserver<TRequest, TResponse> consumerStreamObserver = new RxConsumerStreamObserver<TRequest, TResponse>();
rxRequest.subscribe(new Consumer<TRequest>() {
@Override
public void accept(TRequest request) {
delegate.accept(request, consumerStreamObserver);
}
});
return ((Flowable<TResponse>) consumerStreamObserver.getRxConsumer())
.lift(new SubscribeOnlyOnceFlowableOperator<TResponse>());
} catch (Throwable throwable) {
return Flowable.error(throwable);
}
}
示例3: main
import io.reactivex.Single; //导入方法依赖的package包/类
public static void main(String[] args) {
// TODO Auto-generated method stub
Single<List<String>> month_maybe = Single.create(emitter -> {
try {
String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov",
"Dec" };
List<String> months = Arrays.asList(monthArray);
if (months != null && !months.isEmpty()) {
emitter.onSuccess(months);
}
} catch (Exception e) {
emitter.onError(e);
}
});
month_maybe.subscribe(s->System.out.println(s));
}
示例4: fetchFailsWhenThereAreNoReleases
import io.reactivex.Single; //导入方法依赖的package包/类
@Test
public void fetchFailsWhenThereAreNoReleases() throws Exception {
final FileSystem fs = Jimfs.newFileSystem();
final RecipeSource recipeSource = GitProviderRecipeSource.of(fs, GitHubGitProvider.of());
final Single<Recipe> task = recipeSource.fetch(
RecipeIdentifier.of("github", "njlr", "test-lib-no-releases"))
.result();
final SettableFuture<Throwable> futureException = SettableFuture.create();
task.subscribe(
result -> {
}, error -> {
futureException.set(error);
});
final Throwable exception = futureException.get(90, TimeUnit.SECONDS);
assertTrue(exception instanceof RecipeFetchException);
}
示例5: fetchFailsWhenThereIsNoProjectFile
import io.reactivex.Single; //导入方法依赖的package包/类
@Test
public void fetchFailsWhenThereIsNoProjectFile() throws Exception {
final FileSystem fs = Jimfs.newFileSystem();
final RecipeSource recipeSource = GitProviderRecipeSource.of(fs, GitHubGitProvider.of());
final Single<Recipe> task = recipeSource.fetch(
RecipeIdentifier.of("github", "njlr", "test-lib-no-project"))
.result();
final SettableFuture<Throwable> futureException = SettableFuture.create();
task.subscribe(
result -> {
}, error -> {
futureException.set(error);
});
final Throwable exception = futureException.get(90, TimeUnit.SECONDS);
assertTrue(exception instanceof RecipeFetchException);
}
示例6: storeInDatabase
import io.reactivex.Single; //导入方法依赖的package包/类
private void storeInDatabase(JsonObject operation) {
// 1. need to retrieve a connection
// 2. execute the insertion statement
// 3. close the connection
// Step 1 get the connection
Single<SQLConnection> connectionRetrieved = jdbc.rxGetConnection();
// Step 2, when the connection is retrieved (this may have failed), do the insertion (upon success)
Single<UpdateResult> update = connectionRetrieved
.flatMap(connection ->
connection.rxUpdateWithParams(INSERT_STATEMENT, new JsonArray().add(operation.encode()))
// Step 3, when the insertion is done, close the connection.
.doAfterTerminate(connection::close));
update.subscribe(result -> {
// Ok
}, err -> {
System.err.println("Failed to insert operation in database: " + err);
});
}
示例7: testSingle
import io.reactivex.Single; //导入方法依赖的package包/类
@Test
public void testSingle() {
publisher.setQueryResult(listResult);
Single single = RxQuery.single(mockQuery.getQuery());
single.subscribe((SingleObserver) this);
assertLatchCountedDown(latch, 2);
assertEquals(1, receivedChanges.size());
assertEquals(2, receivedChanges.get(0).size());
receivedChanges.clear();
publisher.publish();
assertNoMoreResults();
}
示例8: test_Single
import io.reactivex.Single; //导入方法依赖的package包/类
@Test
public void test_Single() {
Single<String> single = Single.just("FRUITS");
TestObserver<String> testObserver = new TestObserver<>();
single.subscribe(testObserver);
testObserver.assertComplete();
testObserver.assertValueCount(1);
testObserver.assertNoErrors();
testObserver.assertValues("FRUITS");
}
示例9: main
import io.reactivex.Single; //导入方法依赖的package包/类
public static void main(String[] args) {
String[] fruits = { "mango", "pineapple", "apple", "mango", "papaya", "pineapple", "apple", "apple" };
Single<Long> sing = Observable.fromArray(fruits).distinctUntilChanged().count();
sing.subscribe(System.out::println);
Observable.fromArray(fruits).distinctUntilChanged().subscribe(new Observer<String>() {
@Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("collected all items successfully");
}
@Override
public void onError(Throwable throwable) {
// TODO Auto-generated method stub
throwable.printStackTrace();
}
@Override
public void onNext(String value) {
// TODO Auto-generated method stub
System.out.println("collected item: " + value);
}
@Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
}
});
}
开发者ID:PacktPublishing,项目名称:Reactive-Programming-With-Java-9,代码行数:37,代码来源:Demo_distinctUntilChanged.java
示例10: main
import io.reactivex.Single; //导入方法依赖的package包/类
public static void main(String[] args) {
// TODO Auto-generated method stub
Single<Boolean> single = Observable.fromArray(Arrays.asList(new Integer[] { 2, 12, 5, 70, 110 })).
all(item -> {
boolean flag = false;
for (int i : item) {
if (i % 2 != 0) {
return false;
}
}
return true;
});
single.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean passed) throws Exception {
// TODO Auto-generated method stub
System.out.println(passed);
}
});
// Observable source1 = Observable.range(3, 5);
// source1.takeWhile(new Predicate<Integer>() {
//
// @Override
// public boolean test(Integer arg0) throws Exception {
// // TODO Auto-generated method stub
// if (arg0 > 5)
// return false;
// return true;
// }
// }).subscribe(System.out::println);
}
示例11: main
import io.reactivex.Single; //导入方法依赖的package包/类
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] fruits= {"mango","pineapple","apple","mango","papaya","pineapple","apple","apple"};
Single<Long> sing=Observable.fromArray(fruits).distinct().count();
sing.subscribe(System.out::println);
Observable.fromArray(fruits).distinct().subscribe(new Observer<String>() {
@Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("collected all distinct items successfully");
}
@Override
public void onError(Throwable throwable) {
// TODO Auto-generated method stub
throwable.printStackTrace();
}
@Override
public void onNext(String value) {
// TODO Auto-generated method stub
System.out.println("collected item: "+value);
}
@Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
}});
}
示例12: deploy
import io.reactivex.Single; //导入方法依赖的package包/类
static void deploy(final Vertx vertx,
final Class<?> clazz,
final DeploymentOptions options,
final Annal logger) {
final String name = clazz.getName();
final String flag = options.isWorker() ? "Rx-Worker" : "Rx-Agent";
final Single<String> observable
= vertx.rxDeployVerticle(clazz.getName(), options);
observable.subscribe(
(item) -> logger.info(Info.VTC_END, name, options.getInstances(), item, flag),
(cause) -> logger.info(Info.VTC_FAIL, name, options.getInstances(),
null == cause.getCause() ? null : cause.getCause().getMessage(), flag));
}
示例13: makeRequest
import io.reactivex.Single; //导入方法依赖的package包/类
/**
* Create new retrofit api request
* @param request single api request
* @param shouldUpdateUi true if should update UI after request done
* @param responseConsumer consume parsed response data (in pojo object)
* @param errorConsumer consume {@link ErrorEntity} object which is construct by which error is occurred
* with a code and an message (will be shown to user)
* the error might by a HttpException, Runtime Exception, or an error respond from back-end api...
*
* @param <T> Type of response body
* @return a disposable
*/
public static <T> Disposable makeRequest(
Single<T> request, boolean shouldUpdateUi,
@NonNull PlainConsumer<T> responseConsumer,
@Nullable PlainConsumer<ErrorEntity> errorConsumer) {
Single<T> single = request.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io());
if (shouldUpdateUi) {
single = single.observeOn(AndroidSchedulers.mainThread());
}
return single.subscribe(responseConsumer, throwable -> {
// handle error
throwable.printStackTrace();
if (errorConsumer != null) {
int code = ResponseHelper.getErrorCode(throwable);
String message;
GitHubErrorResponse errorResponse = ResponseHelper.getErrorResponse(throwable);
if (errorResponse != null && errorResponse.getMessage() != null) {
message = errorResponse.getMessage();
} else {
message = ResponseHelper.getPrettifiedErrorMessage(throwable);
}
errorConsumer.accept(new ErrorEntity(message, code));
}
});
}
示例14: putMetadata
import io.reactivex.Single; //导入方法依赖的package包/类
@Override
public Disposable putMetadata(Single<Metadata> metadata) {
return metadata.subscribe(m -> {
final File file = new File(directory, "config.json");
try {
FileUtils.writeStringToFile(file, m.getTileJson().toString(), "UTF-8");
} catch (final IOException ex) {
LOG.error("problem writing metadata", ex);
}
});
}
示例15: evaluate
import io.reactivex.Single; //导入方法依赖的package包/类
@Override
public void evaluate(Handler<AsyncResult<Double>> resultHandler) {
// TODO
// ----
Single<WebClient> quotes = HttpEndpoint.rxGetWebClient(discovery, rec -> rec.getName().equals("quote-generator"));
quotes.subscribe((client, err) -> {
if (err != null) {
resultHandler.handle(Future.failedFuture(err));
} else {
computeEvaluation(client, resultHandler);
}
});
// ---
}