Java Code Examples for io.reactivex.Observable#just()

The following examples show how to use io.reactivex.Observable#just() . 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: PageLoaderEpub.java    From a with GNU General Public License v3.0 6 votes vote down vote up
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());
                });
    }
}
 
Example 2
Source File: PostViewActivity.java    From quill with MIT License 6 votes vote down vote up
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));
}
 
Example 3
Source File: SearchInteractor.java    From mosby with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 4
Source File: CacheManager.java    From RxCache with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: NotYetSupportedTest.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 6
Source File: TransactionServiceImpl.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
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())));
}
 
Example 7
Source File: DashboardRepositoryImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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);
    }
}
 
Example 8
Source File: WindowIfChangedTest.java    From RxWindowIfChanged with Apache License 2.0 5 votes vote down vote up
@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()); //
}
 
Example 9
Source File: Demo.java    From rxjava-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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())
    );
}
 
Example 10
Source File: Demo_Create_Observable.java    From Reactive-Programming-With-Java-9 with MIT License 4 votes vote down vote up
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));
}
 
Example 11
Source File: ReduceExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 4 votes vote down vote up
private Observable<Integer> getObservable() {
    return Observable.just(1, 2, 3, 4);
}
 
Example 12
Source File: AVFile.java    From java-unified-sdk with Apache License 2.0 4 votes vote down vote up
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);
  }
}
 
Example 13
Source File: CategoryFragment.java    From mosby with Apache License 2.0 4 votes vote down vote up
@Override public Observable<String> loadIntents() {
  return Observable.just(getArguments().getString(CATEGORY_NAME));
}
 
Example 14
Source File: TakeExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 4 votes vote down vote up
private Observable<Integer> getObservable() {
    return Observable.just(1, 2, 3, 4, 5);
}
 
Example 15
Source File: RxPermissionsTest.java    From RxPermissions with Apache License 2.0 4 votes vote down vote up
private Observable<Object> trigger() {
    return Observable.just(RxPermissions.TRIGGER);
}
 
Example 16
Source File: ObservableDeferredResultTest.java    From Java-9-Spring-Webflux with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/multiple")
public ObservableDeferredResult<String> multiple() {
    return new ObservableDeferredResult<>(Observable.just("multiple", "values"));
}
 
Example 17
Source File: AuthFilter.java    From festival with Apache License 2.0 4 votes vote down vote up
@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);
                        }
                    });
}
 
Example 18
Source File: ObservableResourceTest.java    From rx-jersey with MIT License 4 votes vote down vote up
@GET
@Path("multiple")
public Observable<String> multiple() {
    return Observable.just("hello", "rx");
}
 
Example 19
Source File: ProgramEventDetailRepositoryImpl.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NonNull
@Override
public Observable<Program> program() {
    return Observable.just(d2.programModule().programs().uid(programUid).blockingGet());
}
 
Example 20
Source File: RxUserServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public Observable<User> recent(Observable<Date> point) {
    return Observable.just(new User(1, "first"), new User(2, "second"));
}