io.reactivex.Observable Java Examples

The following examples show how to use io.reactivex.Observable. 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: SynchronousColumnQueryTest.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
@Test
public void aliasWithSpaces() {
  final int count = 8;
  final List<String> expected = Observable.fromIterable(insertAuthors(count))
      .map(new Function<Author, String>() {
        @Override
        public String apply(Author v) {
          return v.name;
        }
      })
      .toList()
      .blockingGet();

  assertThat(Select
      .column(AUTHOR.NAME.as("author name"))
      .from(AUTHOR)
      .execute())
      .isEqualTo(expected);
}
 
Example #2
Source File: Permission.java    From RxPermissions with Apache License 2.0 6 votes vote down vote up
private String combineName(List<Permission> permissions) {
    return Observable.fromIterable(permissions)
            .map(new Function<Permission, String>() {
                @Override
                public String apply(Permission permission) throws Exception {
                    return permission.name;
                }
            }).collectInto(new StringBuilder(), new BiConsumer<StringBuilder, String>() {
                @Override
                public void accept(StringBuilder s, String s2) throws Exception {
                    if (s.length() == 0) {
                        s.append(s2);
                    } else {
                        s.append(", ").append(s2);
                    }
                }
            }).blockingGet().toString();
}
 
Example #3
Source File: MnemonicActivity.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
void loginWithMnemonic(final String mnemonic, final String password) {
    startLoading();
    Observable.just(getSession())
    .observeOn(Schedulers.computation())
    .map((session) -> {
        session.disconnect();
        connect();
        session.loginWithMnemonic(mnemonic, password);
        return session;
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe((session) -> {
        onPostLogin();
        stopLoading();
        onLoginSuccess();
    }, (final Throwable e) -> {
        stopLoading();
        GDKSession.get().disconnect();
        final Integer code = getErrorCode(e.getMessage());
        if (code == GDK.GA_ERROR) {
            UI.toast(this, R.string.id_login_failed, Toast.LENGTH_LONG);
        } else {
            UI.toast(this, R.string.id_connection_failed, Toast.LENGTH_LONG);
        }
    });
}
 
Example #4
Source File: EditListNameFragment.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
@Override
protected void observeValidCreate(@NonNull EditText inputView, @NonNull Observable<String> createStream) {
  final long listId = getArguments().getLong(EXTRA_LIST_ID);
  final String currentListName = Select.column(ITEM_LIST.NAME)
      .from(ITEM_LIST)
      .where(ITEM_LIST.ID.is(listId))
      .takeFirst()
      .execute();
  inputView.setText(currentListName);
  inputView.setSelection(currentListName.length());
  createStream.observeOn(Schedulers.io())
      .flatMap(name -> Update
          .table(ITEM_LIST)
          .set(ITEM_LIST.NAME, name)
          .where(ITEM_LIST.ID.is(listId))
          .observe()
          .toObservable())
      .firstOrError()
      .subscribe();
}
 
Example #5
Source File: OnErrorRetryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenSubscriberAndError_whenRetryConditionallyOnError_thenRetryConfirmed() {
    TestObserver<String> testObserver = new TestObserver<>();

    AtomicInteger atomicCounter = new AtomicInteger(0);

    Observable
      .<String>error(() -> {
          atomicCounter.incrementAndGet();
          return UNKNOWN_ERROR;
      })
      .retry((integer, throwable) -> integer < 4)
      .subscribe(testObserver);

    testObserver.assertError(UNKNOWN_ERROR);
    testObserver.assertNotComplete();
    testObserver.assertNoValues();
    assertTrue("should call 4 times", atomicCounter.get() == 4);
}
 
Example #6
Source File: TimeoutExample.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    Observable<String> source = Observable.create(emitter -> {
        emitter.onNext("A");
        Thread.sleep(800);
        emitter.onNext("B");
        Thread.sleep(400);
        emitter.onNext("C");
        Thread.sleep(1200);
        emitter.onNext("D");
        emitter.onComplete();
    });
    source.timeout(1, TimeUnit.SECONDS)
            .subscribe(
                    item -> System.out.println("onNext: " + item),
                    error -> System.out.println("onError: " + error),
                    () -> System.out.println("onComplete will not be printed!"));
}
 
Example #7
Source File: WindowIfChangedTest.java    From RxWindowIfChanged with Apache License 2.0 6 votes vote down vote up
@Test public void completeCompletesInner() {
  Observable<Message> messages = Observable.just(new Message("Bob", "Hello"));
  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.<String>createOnComplete()) //
      .assertComplete();
}
 
Example #8
Source File: WebBook.java    From a with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取目录
 */
public Observable<List<BookChapterBean>> getChapterList(final BookShelfBean bookShelfBean) {
    if (bookSourceBean == null) {
        return Observable.error(new NoSourceThrowable(bookShelfBean.getBookInfoBean().getName()));
    }
    BookChapterList bookChapterList = new BookChapterList(tag, bookSourceBean, true);
    if (!TextUtils.isEmpty(bookShelfBean.getBookInfoBean().getChapterListHtml())) {
        return bookChapterList.analyzeChapterList(bookShelfBean.getBookInfoBean().getChapterListHtml(), bookShelfBean, headerMap);
    }
    try {
        AnalyzeUrl analyzeUrl = new AnalyzeUrl(bookShelfBean.getBookInfoBean().getChapterUrl(), headerMap, bookShelfBean.getNoteUrl());
        return getResponseO(analyzeUrl)
                .flatMap(response -> setCookie(response, tag))
                .flatMap(response -> bookChapterList.analyzeChapterList(response.body(), bookShelfBean, headerMap));
    } catch (Exception e) {
        return Observable.error(new Throwable(String.format("url错误:%s", bookShelfBean.getBookInfoBean().getChapterUrl())));
    }
}
 
Example #9
Source File: OperatorsTest.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 6 votes vote down vote up
@Test
void distinct_test() {
    Observable<LocalDate> dates = Observable.just(
            LocalDate.of(2018, 1, 3),
            LocalDate.of(2018, 3, 4),
            LocalDate.of(2018, 1, 5),
            LocalDate.of(2018, 11, 3)
    );
    //	get	distinct	months
    dates.map(LocalDate::getMonth)
         .distinct()
         .subscribe(System.out::println);
    System.out.println("############################");
    //	get	distinct	days
    dates.distinct(LocalDate::getMonth)
         .subscribe(System.out::println);
}
 
Example #10
Source File: DataSetCompleteRegistrationPostCall.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Observable<D2Progress> uploadDataSetCompleteRegistrations(
        List<DataSetCompleteRegistration> dataSetCompleteRegistrations) {
    return Observable.defer(() -> {
        if (dataSetCompleteRegistrations.isEmpty()) {
            return Observable.empty();
        } else {
            List<DataSetCompleteRegistration> toPostDataSetCompleteRegistrations = new ArrayList<>();
            List<DataSetCompleteRegistration> toDeleteDataSetCompleteRegistrations = new ArrayList<>();

            for (DataSetCompleteRegistration dscr: dataSetCompleteRegistrations) {
                if (dscr.deleted()) {
                    toDeleteDataSetCompleteRegistrations.add(dscr);
                } else {
                    toPostDataSetCompleteRegistrations.add(dscr);
                }
            }

            D2ProgressManager progressManager = new D2ProgressManager(2);

            return systemInfoDownloader.downloadMetadata().andThen(Observable.create(emitter -> {
                emitter.onNext(progressManager.increaseProgress(SystemInfo.class, false));

                uploadInternal(progressManager, emitter, toPostDataSetCompleteRegistrations,
                        toDeleteDataSetCompleteRegistrations);
            }));
        }
    });
}
 
Example #11
Source File: ObservableGroup.java    From RxGroups with Apache License 2.0 5 votes vote down vote up
/**
 * Adds an {@link Observable} and {@link Observer} to this group and subscribes to it. If an
 * {@link Observable} with the same tag is already added, the previous one will be canceled and
 * removed before adding and subscribing to the new one.
 */
<T> ManagedObservable<T> add(final String observerTag, final String observableTag,
    Observable<T> observable, ObservableEmitter<? super T> observer) {
  checkNotDestroyed();
  final Map<String, ManagedObservable<?>> existingObservables =
      getObservablesForObserver(observerTag);
  ManagedObservable<?> previousObservable = existingObservables.get(observableTag);

  if (previousObservable != null) {
    cancelAndRemove(observerTag, observableTag);
  }

  ManagedObservable<T> managedObservable =
      new ManagedObservable<>(observerTag, observableTag, observable, observer, new
          Action() {
            @Override
            public void run() {
              existingObservables.remove(observableTag);
            }
          });

  existingObservables.put(observableTag, managedObservable);

  if (!locked) {
    managedObservable.unlock();
  }
  return managedObservable;
}
 
Example #12
Source File: UpLastChapterModel.java    From a with GNU General Public License v3.0 5 votes vote down vote up
private Observable<BookShelfBean> toBookshelf(SearchBookBean searchBookBean) {
    return Observable.create(e -> {
        BookShelfBean bookShelfBean = BookshelfHelp.getBookFromSearchBook(searchBookBean);
        e.onNext(bookShelfBean);
        e.onComplete();
    });
}
 
Example #13
Source File: StreamVsRxJava.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
public void rx2oSerial() {
    Observable.fromIterable(rows)
    .flatMap(r -> {
        String[] ws = r.split("\\s");
        return Observable.fromArray(ws);
    })
    .filter(w -> w.length() > 4)
    .map(w -> w.length())
    .reduce(0, (a, b) -> a + b)
    .subscribe()
    ;
}
 
Example #14
Source File: HangmanTest.java    From java with MIT License 5 votes vote down vote up
@Ignore("Remove to run test")
@Test
public void cannotPlayAGuessTwice() {
    Observable<Output> result = hangman.play(
        Observable.fromArray("secret"),
        Observable.fromArray("e", "c", "s", "c"));

    assertThatThrownBy(() -> result.blockingLast())
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessageContaining("Letter c was already played");
}
 
Example #15
Source File: UpLastChapterModel.java    From a with GNU General Public License v3.0 5 votes vote down vote up
private Observable<SearchBookBean> saveSearchBookBean(List<BookChapterBean> chapterBeanList) {
    return Observable.create(e -> {
        BookChapterBean chapterBean = chapterBeanList.get(chapterBeanList.size() - 1);
        SearchBookBean searchBookBean = DbHelper.getDaoSession().getSearchBookBeanDao().queryBuilder()
                .where(SearchBookBeanDao.Properties.NoteUrl.eq(chapterBean.getNoteUrl()))
                .unique();
        if (searchBookBean != null) {
            searchBookBean.setLastChapter(chapterBean.getDurChapterName());
            searchBookBean.setAddTime(System.currentTimeMillis());
            DbHelper.getDaoSession().getSearchBookBeanDao().insertOrReplace(searchBookBean);
            e.onNext(searchBookBean);
        }
        e.onComplete();
    });
}
 
Example #16
Source File: AvoidOnResultFragment.java    From AvoidOnResult with Apache License 2.0 5 votes vote down vote up
public Observable<ActivityResultInfo> startForResult(final Intent intent) {
    final PublishSubject<ActivityResultInfo> subject = PublishSubject.create();
    return subject.doOnSubscribe(new Consumer<Disposable>() {
        @Override
        public void accept(Disposable disposable) throws Exception {
            int requestCode = generateRequestCode();
            mSubjects.put(requestCode, subject);
            startActivityForResult(intent, requestCode);
        }
    });
}
 
Example #17
Source File: StubActivity.java    From Reactive-Android-Programming with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mock);

    subscribe = Observable.interval(1, TimeUnit.SECONDS)
            .subscribe();
}
 
Example #18
Source File: ObservableTest.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
@Test
void just_test() {
    log("Just_test Before");
    Observable
            .just("Jan", "Feb", "Mar", "Apl", "May", "Jun")
            .subscribe(ObservableTest::log);
    log("Just_test After");
}
 
Example #19
Source File: AppApiHelper.java    From v9porn with MIT License 5 votes vote down vote up
@Override
public Observable<AxgleResponse> axgleVideos(int page, String o, String t, String type, String c, int limit) {
    return axgleServiceApi.videos(page, o, t, type, c, limit).map(s -> {
        Axgle axgle = gson.fromJson(s, Axgle.class);
        return axgle.getResponse();
    });
}
 
Example #20
Source File: AppDbHelper.java    From android-mvp-architecture with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Boolean> isOptionEmpty() {
    return Observable.fromCallable(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return !(mDaoSession.getOptionDao().count() > 0);
        }
    });
}
 
Example #21
Source File: TransactionServiceImpl.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<AggregateTransaction> announceAggregateBonded(
    Listener listener, SignedTransaction signedAggregateTransaction) {
    Validate.notNull(signedAggregateTransaction, "signedAggregateTransaction is required");
    Validate.isTrue(signedAggregateTransaction.getType() == TransactionType.AGGREGATE_BONDED,
        "signedAggregateTransaction type must be AGGREGATE_BONDED");
    Observable<TransactionAnnounceResponse> announce = transactionRepository
        .announceAggregateBonded(signedAggregateTransaction);
    return announce.flatMap(
        r -> listener.aggregateBondedAddedOrError(signedAggregateTransaction.getSigner().getAddress(),
            signedAggregateTransaction.getHash()));
}
 
Example #22
Source File: PostRequest.java    From RxEasyHttp with Apache License 2.0 5 votes vote down vote up
public <T> Observable<T> execute(CallClazzProxy<? extends ApiResult<T>, T> proxy) {
    return build().generateRequest()
            .map(new ApiResultFunc(proxy.getType()))
            .compose(isSyncRequest ? RxUtil._main() : RxUtil._io_main())
            .compose(rxCache.transformer(cacheMode, proxy.getCallType()))
            .retryWhen(new RetryExceptionFunc(retryCount, retryDelay, retryIncreaseDelay))
            .compose(new ObservableTransformer() {
                @Override
                public ObservableSource apply(@NonNull Observable upstream) {
                    return upstream.map(new CacheResultFunc<T>());
                }
            });
}
 
Example #23
Source File: AsfWeb3jImpl.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Observable<String> call(org.web3j.protocol.core.methods.request.Transaction transaction) {
  return Observable.fromCallable(
      () -> web3j.ethCall(transaction, DefaultBlockParameterName.LATEST)
          .send())
      .map(EthCall::getValue);
}
 
Example #24
Source File: RuleListPresenter.java    From XposedSmsCode with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void importRules(Uri uri, boolean retain, String progressMsg) {
    Disposable disposable = Observable
            .fromCallable(() -> BackupManager.importRuleList(mContext, uri, retain))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(d -> mView.showProgress(progressMsg))
            .subscribe(importResult -> {
                mView.onImportComplete(importResult);
                mView.cancelProgress();
            }, throwable -> {
                // ignore
            });
    mCompositeDisposable.add(disposable);
}
 
Example #25
Source File: WeixinChoiceModel.java    From YiZhi with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<WeixinChoiceListBean> getWeixinChoiceList(int page, int pageStrip, String
        dttype, String key) {
    return RetrofitCreateHelper.createApi(WeixinApi.class, WeixinApi.HOST).getWeixinChoiceList
            (page, pageStrip, dttype, key).compose(RxHelper
            .<WeixinChoiceListBean>rxSchedulerHelper());
}
 
Example #26
Source File: PaginationStreamerTester.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
private <T> List<Observable<Page<T>>> toPages(List<T> infos, Integer pageSize) {
    List<List<T>> partitions = new ArrayList<>();
    for (int i = 0; i < infos.size(); i += pageSize) {
        partitions.add(infos.subList(i, Math.min(i + pageSize, infos.size())));
    }
    AtomicInteger pageNumber = new AtomicInteger();
    return partitions.stream().map(
        pageData -> Observable
            .just(new Page<T>(pageData, pageNumber.incrementAndGet(), pageSize, infos.size(), partitions.size())))
        .collect(Collectors.toList());
}
 
Example #27
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Observable<DataSnapshot> changes(@NonNull final Query query) {
    return Observable.create(new ObservableOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final ObservableEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (!emit.isDisposed()) {
                        emit.onNext(dataSnapshot);
                    }
                }

                @Override
                public void onCancelled(DatabaseError e) {
                    if (!emit.isDisposed()) {
                        emit.onError(e.toException());
                    }
                }
            };

            emit.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    query.removeEventListener(listener);
                }
            });

            query.addValueEventListener(listener);
        }
    });
}
 
Example #28
Source File: NetTestDataManager.java    From QuickDevFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 获取测试数据
 * */
public Observable<String> getTestData() {
    return clientApi.getWeather("101010100")
    .flatMap(new Function<ResponseBody, ObservableSource<String>>() {
        @Override
        public ObservableSource<String> apply(@NonNull ResponseBody responseBody) throws Exception {
            return Observable.just(responseBody.string());
        }
    });
}
 
Example #29
Source File: OpenIDScopeUpgrader.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public boolean upgrade() {
    logger.info("Applying OIDC scope upgrade");
    domainService.findAll()
            .flatMapObservable(Observable::fromIterable)
            .flatMapSingle(this::createOrUpdateSystemScopes)
            .subscribe();
    return true;
}
 
Example #30
Source File: IEntityEndpoint.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@GET("/v3/projects/{id}/merge_requests/{merge_request_id}/comments")
Observable<MRNote> getV3ProjectsMerge_requestsCommentsMRNote( 
		
		@Path(value="id", encoded=true) String id,			
		@Query(value="page", encoded=true) Integer page,			
		@Query(value="per_page", encoded=true) Integer perPage,			
		@Path(value="merge_request_id", encoded=true) Integer mergeRequestId);