下面列出了io.reactivex.Observable#just ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Observable<BookShelfBean> checkChapterList(BookShelfBean collBook) {
if (!collBook.getHasUpdate() && !callback.getChapterList().isEmpty()) {
return Observable.just(collBook);
} else {
return Observable.create((ObservableOnSubscribe<List<BookChapterBean>>) e -> {
List<BookChapterBean> chapterList = loadChapters();
if (!chapterList.isEmpty()) {
e.onNext(chapterList);
} else {
e.onError(new IllegalAccessException("epubBook sub-chapter failed!"));
}
e.onComplete();
})
.flatMap(chapterList -> {
collBook.setChapterListSize(chapterList.size());
callback.onCategoryFinish(chapterList);
return Observable.just(collBook);
})
.doOnNext(bookShelfBean -> {
// 存储章节到数据库
bookShelfBean.setHasUpdate(false);
bookShelfBean.setFinalRefreshData(System.currentTimeMillis());
});
}
}
public void viewPostInBrowser(boolean saveBeforeViewing) {
mbPreviewPost = true;
Observable<Boolean> waitForNetworkObservable;
if (saveBeforeViewing) {
waitForNetworkObservable = mPostEditFragment.onSaveClicked();
} else {
waitForNetworkObservable = Observable.just(false);
}
Consumer<Boolean> waitForNetworkAction = isNetworkCallPending -> {
if (isNetworkCallPending) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage(getString(R.string.save_post_progress));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
mHandler.postDelayed(mSaveTimeoutRunnable, 10000);
} else {
mbPreviewPost = false;
startBrowserActivity(PostUtils.getPostUrl(mPost));
}
};
disposeOnPause(
waitForNetworkObservable.subscribe(waitForNetworkAction));
}
/**
* Search for items
*/
public Observable<SearchViewState> search(String searchString) {
// Empty String, so no search
if (searchString.isEmpty()) {
return Observable.just(new SearchViewState.SearchNotStartedYet());
}
// search for product
return searchEngine.searchFor(searchString)
.map(products -> {
if (products.isEmpty()) {
return new SearchViewState.EmptyResult(searchString);
} else {
return new SearchViewState.SearchResult(searchString, products);
}
})
.startWith(new SearchViewState.Loading())
.onErrorReturn(error -> new SearchViewState.Error(searchString, error));
}
public Observable<Boolean> remove(String... keys) {
if (getCacheMode() == CacheMode.NONE) return Observable.just(true);
boolean result = false;
for (int i = 0; i < keys.length; i++) {
if (getDiskCache() != null) {
result |= getDiskCache().remove(keys[i]);
result |= !getDiskCache().contains(keys[i]);
}
if (getMemoryCache() != null) {
result |= getMemoryCache().remove(keys[i]);
result |= !getMemoryCache().contains(keys[i]);
}
}
return Observable.just(result);
}
/**
* On XMap (ex {@code just(1).concatMap(..}, the source scalar callable is not passed as an input
* to the subsequent operator like {@code ObservableScalarXMap.ScalarXMapObservable}. What is
* passed is the result of {@link ScalarCallable#call()}.
*
* <p>Usually, this would result in lost tracking of the assembled context. However, we use a
* thread local to stash the context between {@link ScalarCallable#call()} and the next {@link
* RxJavaPlugins#onAssembly assembly hook}.
*
* @see ObservableScalarXMap#scalarXMap - references to this are operators which require stashing
*/
@Test(expected = AssertionError.class)
public void observable_scalarCallable_propagatesContextOnXMap() {
Observable<Integer> fuseable;
try (Scope scope1 = currentTraceContext.newScope(assemblyContext)) {
fuseable = Observable.just(1);
assertThat(fuseable).isInstanceOf(ScalarCallable.class);
}
// eventhough upstream is assembled with XMap, we still inherit the fused context.
fuseable = fuseable.concatMap(Observable::just);
assertXMapFusion(fuseable).test().assertValues(1).assertNoErrors();
}
@Override
public Observable<Boolean> updateEnrollmentStatus(String enrollmentUid, EnrollmentStatus status) {
try {
if(d2.programModule().programs().uid(programUid).blockingGet().access().data().write()) {
d2.enrollmentModule().enrollments().uid(enrollmentUid).setStatus(status);
return Observable.just(true);
}
return Observable.just(false);
} catch (D2Error error){
return Observable.just(false);
}
}
@Test public void splits() {
Observable<Message> messages = Observable.just( //
new Message("Bob", "Hello"), //
new Message("Bob", "World"), //
new Message("Alice", "Hey"), //
new Message("Bob", "What's"), //
new Message("Bob", "Up?"), //
new Message("Eve", "Hey") //
);
final AtomicInteger seen = new AtomicInteger();
WindowIfChanged.create(messages, userSelector)
.switchMap(
new Function<GroupedObservable<String, Message>, Observable<Notification<String>>>() {
@Override public Observable<Notification<String>> apply(
GroupedObservable<String, Message> group) {
final int count = seen.incrementAndGet();
return group.map(new Function<Message, String>() {
@Override public String apply(Message message) throws Exception {
return count + " " + message;
}
}).materialize();
}
})
.test()
.assertValues( //
Notification.createOnNext("1 Bob Hello"), //
Notification.createOnNext("1 Bob World"), //
Notification.<String>createOnComplete(), //
Notification.createOnNext("2 Alice Hey"), //
Notification.<String>createOnComplete(), //
Notification.createOnNext("3 Bob What's"), //
Notification.createOnNext("3 Bob Up?"), //
Notification.<String>createOnComplete(), //
Notification.createOnNext("4 Eve Hey"), //
Notification.<String>createOnComplete()); //
}
@RequestMapping(method = RequestMethod.GET, value = "/invoices", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Observable<Invoice> getInvoices() {
return Observable.just(
new Invoice("Acme", new Date()),
new Invoice("Oceanic", new Date())
);
}
private Observable<MosaicId> getResolvedMosaicId(
Transaction transaction,
UnresolvedMosaicId unresolvedMosaicId,
Observable<Statement> statementObservable, ReceiptSource expectedReceiptSource) {
if (unresolvedMosaicId instanceof MosaicId) {
return Observable.just((MosaicId) unresolvedMosaicId);
}
return statementObservable.map(statement -> statement
.getResolvedMosaicId(getTransactionInfo(transaction).getHeight(), unresolvedMosaicId,
expectedReceiptSource.getPrimaryId(),
expectedReceiptSource.getSecondaryId())
.orElseThrow(() -> new IllegalArgumentException(
"MosaicId could not be resolved for alias "
+ unresolvedMosaicId.getIdAsHex())));
}
@Override
public void doFilter(RoutingContext routingContext, FilterChain filterChain) throws Exception {
RouteAttribute routeAttribute = (RouteAttribute) routingContext.data()
.get(RouteManager.ROUTE_ATTRIBETE_KEY);
if (routeAttribute == null || !routeAttribute.isAuth() || routeAttribute.isPermitAll()) {
filterChain.doFilter(routingContext);
return;
}
PermitHolder permitAllowed = routeAttribute.getPermitAllowed();
Observable<Boolean> permitObservable = Observable.just(true);
if (permitAllowed != null) {
permitObservable = SecurityUtils.isPermited(User.newInstance(routingContext.user()), permitAllowed.getPermits(), permitAllowed.getLogicType());
}
PermitHolder rolesAllowed = routeAttribute.getRolesAllowed();
Observable<Boolean> rolesObservable = Observable.just(true);
if (rolesAllowed != null) {
rolesObservable = SecurityUtils.isPermited(User.newInstance(routingContext.user()), rolesAllowed.getPermits(), rolesAllowed.getLogicType());
}
Observable.combineLatest(permitObservable, rolesObservable,
new BiFunction<Boolean, Boolean, Boolean>() {
@Override
public Boolean apply(Boolean res1, Boolean res2) throws Exception {
return res1 && res2;
}
})
.subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean res) throws Exception {
if (res) {
filterChain.doFilter(routingContext);
return;
}
if (deniedHandler != null) {
deniedHandler.handle(routingContext);
} else {
if (log.isTraceEnabled()) {
log.trace("do default permit denied handler!");
}
routingContext.response().setStatusCode(403).end("permisson denied!");
}
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable e) throws Exception {
if (log.isErrorEnabled()) {
log.error(e.getMessage(), e);
}
routingContext.fail(500, e);
}
});
}
@Override
public Observable<User> recent(Observable<Date> point) {
return Observable.just(new User(1, "first"), new User(2, "second"));
}
@NonNull
@Override
public Observable<Program> program() {
return Observable.just(d2.programModule().programs().uid(programUid).blockingGet());
}
@GET
@Path("multiple")
public Observable<String> multiple() {
return Observable.just("hello", "rx");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Observable observable=Observable.just("Welcome to RxJava");
observable.subscribe(s->System.out.println(s));
}
@RequestMapping(method = RequestMethod.GET, value = "/multiple")
public ObservableDeferredResult<String> multiple() {
return new ObservableDeferredResult<>(Observable.just("multiple", "values"));
}
private Observable<Object> trigger() {
return Observable.just(RxPermissions.TRIGGER);
}
private Observable<Integer> getObservable() {
return Observable.just(1, 2, 3, 4, 5);
}
@Override public Observable<String> loadIntents() {
return Observable.just(getArguments().getString(CATEGORY_NAME));
}
private Observable<AVFile> saveWithProgressCallback(boolean keepFileName, final ProgressCallback callback) {
JSONObject paramData = generateChangedParam();
final String fileKey = FileUtil.generateFileKey(this.getName(), keepFileName);
paramData.put("key", fileKey);
paramData.put("__type", "File");
if (StringUtil.isEmpty(getObjectId())) {
if (!StringUtil.isEmpty(getUrl())) {
return directlyCreate(paramData);
}
logger.d("createToken params: " + paramData.toJSONString() + ", " + this);
StorageClient storageClient = PaasClient.getStorageClient();
Observable<AVFile> result = storageClient.newUploadToken(paramData)
.map(new Function<FileUploadToken, AVFile>() {
public AVFile apply(@NonNull FileUploadToken fileUploadToken) throws Exception {
logger.d("[Thread:" + Thread.currentThread().getId() + "]" + fileUploadToken.toString() + ", " + AVFile.this);
AVFile.this.setObjectId(fileUploadToken.getObjectId());
AVFile.this.internalPutDirectly(KEY_OBJECT_ID, fileUploadToken.getObjectId());
AVFile.this.internalPutDirectly(KEY_BUCKET, fileUploadToken.getBucket());
AVFile.this.internalPutDirectly(KEY_PROVIDER, fileUploadToken.getProvider());
AVFile.this.internalPutDirectly(KEY_FILE_KEY, fileKey);
Uploader uploader = new FileUploader(AVFile.this, fileUploadToken, callback);
AVFile.this.internalPutDirectly(KEY_URL, fileUploadToken.getUrl());
AVException exception = uploader.execute();
JSONObject completeResult = new JSONObject();
completeResult.put("result", null == exception);
completeResult.put("token",fileUploadToken.getToken());
logger.d("file upload result: " + completeResult.toJSONString());
try {
PaasClient.getStorageClient().fileCallback(completeResult);
if (null != exception) {
logger.w("failed to invoke fileCallback. cause:", exception);
throw exception;
} else {
return AVFile.this;
}
} catch (IOException ex) {
logger.w(ex);
throw ex;
}
}
});
result = storageClient.wrapObservable(result);
return result;
} else {
logger.d("file has been upload to cloud, ignore update request.");
return Observable.just(this);
}
}
private Observable<Integer> getObservable() {
return Observable.just(1, 2, 3, 4);
}