Java Code Examples for io.reactivex.Single

The following are top voted examples for showing how to use io.reactivex.Single. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: RxShell   File: RootKiller.java   View source code 6 votes vote down vote up
static Single<List<String>> makeMiniHarvester(InputStream inputStream) {
    return Observable
            .create((ObservableOnSubscribe<String>) emitter -> {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                LineReader lineReader = new LineReader();
                String line;
                try {
                    while ((line = lineReader.readLine(reader)) != null && !emitter.isDisposed()) {
                        emitter.onNext(line);
                    }
                } catch (IOException e) {
                    if (RXSDebug.isDebug()) Timber.tag(TAG).d("MiniHarvester read error: %s", e.getMessage());
                } finally {
                    emitter.onComplete();
                }
            })
            .doOnEach(n -> { if (RXSDebug.isDebug()) Timber.tag(TAG).v("miniHarvesters:doOnEach %s", n); })
            .subscribeOn(Schedulers.io())
            .toList()
            .onErrorReturnItem(new ArrayList<>())
            .cache();
}
 
Example 2
Project: FireBaseTest   File: ContentPresenterTest.java   View source code 6 votes vote down vote up
@Test
public void loadingErrorAtRepository_UpdateViewModelToDisplayError() {

    when(contentRepository.getContentItem(anyInt())).thenReturn(Single.error(new RuntimeException()));

    assertTrue(viewModel.isShowLoadingIndicator());
    assertFalse(viewModel.isShowErrorMessage());

    contentPresenter.loadContent();
    testScheduler.triggerActions();

    assertFalse(viewModel.isShowLoadingIndicator());
    assertTrue(viewModel.isShowErrorMessage());
    assertNull(viewModel.getContentDescription());
    assertNull(viewModel.getImageUrl());
}
 
Example 3
Project: Phoenix-for-VK   File: WallsImpl.java   View source code 6 votes vote down vote up
@Override
public Single<Post> getById(int accountId, int ownerId, int postId) {
    final IdPair id = new IdPair(postId, ownerId);

    return networker.vkDefault(accountId)
            .wall()
            .getById(Collections.singleton(id), true, 5, Constants.MAIN_OWNER_FIELDS)
            .flatMap(response -> {
                if(isEmpty(response.posts)){
                    throw new NotFoundException();
                }

                List<Owner> owners = Dto2Model.transformOwners(response.profiles, response.groups);

                List<VKApiPost> dtos = response.posts;
                VKApiPost dto = dtos.get(0);

                VKOwnIds ids = new VKOwnIds().append(dto);
                return ownersInteractor.findBaseOwnersDataAsBundle(accountId, ids.getAll(), IOwnersInteractor.MODE_ANY, owners)
                        .map(bundle -> Dto2Model.transform(dto, bundle));
            });
}
 
Example 4
Project: Phoenix-for-VK   File: KeysPersistStore.java   View source code 6 votes vote down vote up
@Override
public Single<Optional<AesKeyPair>> findLastKeyPair(int accountId, int peerId) {
    return Single.create(e -> {
        Uri uri = MessengerContentProvider.getKeysContentUriFor(accountId);
        Cursor cursor = getContext().getContentResolver()
                .query(uri, null, KeyColumns.PEER_ID + " = ?",
                        new String[]{String.valueOf(peerId)}, KeyColumns._ID + " DESC LIMIT 1");

        AesKeyPair pair = null;
        if(nonNull(cursor)){
            if(cursor.moveToNext()){
                pair = map(cursor).setAccountId(accountId);
            }

            cursor.close();
        }

        e.onSuccess(Optional.wrap(pair));
    });
}
 
Example 5
Project: Phoenix-for-VK   File: MessagesStore.java   View source code 6 votes vote down vote up
@Override
public Single<Integer> calculateUnreadCount(int accountId, int peerId) {
    return Single.fromCallable(() -> {
        int result = 0;
        Cursor cursor = DBHelper.getInstance(getContext(), accountId)
                .getReadableDatabase()
                .rawQuery("SELECT COUNT(" + MessageColumns._ID + ") FROM " + MessageColumns.TABLENAME +
                                " WHERE " + MessageColumns.PEER_ID + " = ?" +
                                " AND " + MessageColumns.READ_STATE + " = ?" +
                                " AND " + MessageColumns.OUT + " = ?" +
                                " AND " + MessageColumns.ATTACH_TO + " = ?" +
                                " AND " + MessageColumns.DELETED + " = ?",
                        new String[]{String.valueOf(peerId), "0", "0", "0", "0"});

        if (cursor.moveToNext()) {
            result = cursor.getInt(0);
        }

        cursor.close();
        return result;
    });
}
 
Example 6
Project: Phoenix-for-VK   File: RelationshipInteractor.java   View source code 6 votes vote down vote up
@Override
public Single<Integer> deleteFriends(int accountId, int userId) {
    return networker.vkDefault(accountId)
            .friends()
            .delete(userId)
            .map(response -> {
                if(response.friend_deleted){
                    return DeletedCodes.FRIEND_DELETED;
                }

                if(response.in_request_deleted){
                    return DeletedCodes.IN_REQUEST_DELETED;
                }

                if(response.out_request_deleted){
                    return DeletedCodes.OUT_REQUEST_DELETED;
                }

                if(response.suggestion_deleted){
                    return DeletedCodes.SUGGESTION_DELETED;
                }

                throw new UnepectedResultException();
            });
}
 
Example 7
Project: Phoenix-for-VK   File: DatabaseInteractor.java   View source code 6 votes vote down vote up
@Override
public Single<List<Chair>> getChairs(int accoutnId, int facultyId, int count, int offset) {
    return networker.vkDefault(accoutnId)
            .database()
            .getChairs(facultyId, offset, count)
            .map(items -> {
                List<ChairDto> dtos = Utils.listEmptyIfNull(items.getItems());
                List<Chair> chairs = new ArrayList<>(dtos.size());

                for(ChairDto dto : dtos){
                    chairs.add(new Chair(dto.id, dto.title));
                }

                return chairs;
            });
}
 
Example 8
Project: RxLifeCycle   File: UntilLifecycleTransformerSingleTest.java   View source code 6 votes vote down vote up
@Test
public void oneEvent() {
    TestObserver<String> testObserver = Single.just("1")
        .delay(1, TimeUnit.MILLISECONDS, testScheduler)
        .compose(RxLifecycle.<String, String>bind(lifecycle))
        .test();

    testObserver.assertNoValues();
    testObserver.assertNoErrors();

    lifecycle.onNext("stop");
    testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);

    testObserver.assertNoValues();
    testObserver.assertError(CancellationException.class);
}
 
Example 9
Project: Phoenix-for-VK   File: KeysRamStore.java   View source code 6 votes vote down vote up
@Override
public Single<List<AesKeyPair>> getKeys(int accountId, int peerId) {
    return Single.create(e -> {
        List<AesKeyPair> list = mData.get(accountId);
        List<AesKeyPair> result = new ArrayList<>(Objects.isNull(list) ? 0 : 1);
        if (Objects.nonNull(list)) {
            for (AesKeyPair pair : list) {
                if (pair.getPeerId() == peerId) {
                    result.add(pair);
                }
            }
        }

        e.onSuccess(result);
    });
}
 
Example 10
Project: Android-Allocine-Api   File: AllocineApi.java   View source code 5 votes vote down vote up
/**
 * Recherche
 */
public Single<AllocineResponseSmall> searchSmall(final String recherche, final List<String> filter, final int count, final int page) {
    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.Q, "" + recherche.replace(" ", "+"),
                            AllocineService.FILTER, filter,
                            AllocineService.COUNT, "" + count,
                            AllocineService.PAGE, "" + page
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<AllocineResponseSmall>>() {
                @Override
                public SingleSource<AllocineResponseSmall> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.searchSmall(recherche, ServiceSecurity.applatir(filter), count, page, pair.first, pair.second);
                }
            })
            .compose(this.<AllocineResponseSmall>retry());
}
 
Example 11
Project: Phoenix-for-VK   File: WallsImpl.java   View source code 5 votes vote down vote up
@Override
public Single<List<Post>> getCachedWall(int accountId, int ownerId, int wallFilter) {
    WallCriteria criteria = new WallCriteria(accountId, ownerId).setMode(wallFilter);
    return repositories.wall()
            .findDbosByCriteria(criteria)
            .compose(dbos2models(accountId));
}
 
Example 12
Project: async-sqs   File: DeleteMessageTaskTest.java   View source code 5 votes vote down vote up
@Test
public void testTaskError() {
    when(requestSenderMock.sendRequest(any())).thenReturn(Single.error(EXCEPTION));
    task.run(QUEUE_URL, ENTRY_MAP);
    ENTRY_MAP.values().forEach((entry) -> entry.getResultSubject().test().assertError(EXCEPTION));
    verify(requestSenderMock).sendRequest(any());
}
 
Example 13
Project: Phoenix-for-VK   File: IFriendsService.java   View source code 5 votes vote down vote up
@FormUrlEncoded
@POST("friends.search")
Single<BaseResponse<Items<VKApiUser>>> search(@Field("user_id") int userId,
                                              @Field("q") String query,
                                              @Field("fields") String fields,
                                              @Field("name_case") String nameCase,
                                              @Field("offset") Integer offset,
                                              @Field("count") Integer count);
 
Example 14
Project: Phoenix-for-VK   File: DocsInteractor.java   View source code 5 votes vote down vote up
@Override
public Single<Document> findById(int accountId, int ownerId, int docId) {
    return networker.vkDefault(accountId)
            .docs()
            .getById(Collections.singletonList(new IdPair(docId, ownerId)))
            .map(dtos -> {
                if(dtos.isEmpty()){
                    throw new NotFoundException();
                }

                return Dto2Model.transform(dtos.get(0));
            });
}
 
Example 15
Project: FCM-for-Mojo   File: DiscussWhitelistActivity.java   View source code 5 votes vote down vote up
@Override
public Single<? extends WhitelistState> startFetchWhitelistState() {
    return Single.zip(FFMService.getDiscussWhitelist(), OpenQQService.getDiscussesInfo(),
            new BiFunction<DiscussWhitelistState, List<Discuss>, DiscussWhitelistState>() {
                @Override
                public DiscussWhitelistState apply(DiscussWhitelistState state, List<Discuss> groups) throws Exception {
                    state.generateStates(groups);
                    return state;
                }
            });
}
 
Example 16
Project: Phoenix-for-VK   File: LogsStore.java   View source code 5 votes vote down vote up
@Override
public Single<List<LogEvent>> getAll(int type) {
    return Single.fromCallable(() -> {
        Cursor cursor = helper().getReadableDatabase().query(LogColumns.TABLENAME, PROJECTION, LogColumns.TYPE  + " = ?",
                        new String[]{String.valueOf(type)}, null, null, LogColumns._ID + " DESC");

        List<LogEvent> data = new ArrayList<>(cursor.getCount());
        while (cursor.moveToNext()){
            data.add(map(cursor));
        }

        cursor.close();
        return data;
    });
}
 
Example 17
Project: wayf-cloud   File: UserRouting.java   View source code 5 votes vote down vote up
public Single<User> getCurrentUser(RoutingContext routingContext) {
    String authorizationHeader = RequestReader.getHeaderValue(routingContext, RequestReader.AUTHORIZATION_HEADER);

    if (authorizationHeader == null) {
        throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "No authorization token provided");
    }

    AuthorizationToken token = authorizationTokenFactory.fromAuthorizationHeader(authorizationHeader);

    return Single.just((User) authenticationFacade.authenticate(token).getAuthenticatable())
            .flatMap((user) -> userFacade.read(user.getId()));
}
 
Example 18
Project: black-mirror   File: LocationDataSource.java   View source code 5 votes vote down vote up
/**
 * Zwraca strefę czasową na podstawie podanej lokalizacji.
   @param location Lokalizacja - miasto, kraj, wieś.
 */
@Override
public Single<TimeZone> getTimeZoneByLocationName(String location) {
    return googleGeoApi.getCoordForLocation(location, GOOGLE_GEO_API_KEY)
            .flatMap(new Function<CoordResponse, SingleSource<? extends TimeZone>>() {
                @Override
                public SingleSource<? extends TimeZone> apply(@NonNull CoordResponse coordResponse) throws Exception {
                    String lat = coordResponse.results.get(0).geometry.location.lat.toString();
                    String lng = coordResponse.results.get(0).geometry.location.lng.toString();
                    return timeZoneDbApi.getTimeZone(lat, lng, TIME_ZONE_DB_API_KEY);
                }
            });
}
 
Example 19
Project: Hubs   File: HubManager.java   View source code 5 votes vote down vote up
@Override
@NonNull
public Single<Hub> readConfig(@NonNull String hubId) {
    return Single.create(emitter -> {
        try {
            emitter.onSuccess(
                    Hub.fromLua(readConfigToString(hubId)));

        } catch (Exception e) {
            emitter.tryOnError(e);
        }
    });
}
 
Example 20
Project: GreenfieldTemplate   File: MockBBCService.java   View source code 5 votes vote down vote up
@Override
public Single<PlaylistResponse> fetchSongs() {
	EspressoIdlingResource.getInstance().increment();
	return Single.just(mockResponse)
			.delay(delay, TimeUnit.MILLISECONDS)
			.subscribeOn(Schedulers.computation())
			.observeOn(AndroidSchedulers.mainThread())
			.doFinally(() -> EspressoIdlingResource.getInstance().decrement());
}
 
Example 21
Project: async-sqs   File: DeleteMessageTaskTest.java   View source code 5 votes vote down vote up
@Test
public void testTaskIndividualError() {
    when(requestSenderMock.sendRequest(any())).thenReturn(Single.just(ERROR_RESULT));
    task.run(QUEUE_URL, ENTRY_MAP);
    ENTRY_MAP.values().forEach((entry) -> entry.getResultSubject().test().assertError(Exception.class));
    verify(requestSenderMock).sendRequest(any());
}
 
Example 22
Project: Phoenix-for-VK   File: PhotosApi.java   View source code 5 votes vote down vote up
@Override
public Single<Boolean> restore(Integer ownerId, int photoId) {
    return provideService(IPhotosService.class, TokenType.USER)
            .flatMap(service -> service.restore(ownerId, photoId)
                    .map(extractResponseWithErrorHandling())
                    .map(response -> response == 1));
}
 
Example 23
Project: REDAndroid   File: UserSearchSearchPresenterTest.java   View source code 5 votes vote down vote up
@Test
public void loadAnnouncementsEmpty() {
    Announcement emptyList = new Announcement();
    emptyList.response = new Announcement.Response();
    emptyList.status = "";
    emptyList.response.announcements = new ArrayList<>();

    stubDataManagerGetAnnouncements(Single.just(emptyList));

    mAnnouncementPresenter.loadAnnouncements();
    verify(mMockAnnouncementMvpView).showProgress(true);
    verify(mMockAnnouncementMvpView).showProgress(false);
    verify(mMockAnnouncementMvpView).showAnnouncementsEmpty();
}
 
Example 24
Project: reactive-grpc   File: ServerCalls.java   View source code 5 votes vote down vote up
/**
 * Implements a unary -> stream call as {@link Single} -> {@link Flowable}, where the server responds with a
 * stream of messages.
 */
public static <TRequest, TResponse> void oneToMany(
        TRequest request, StreamObserver<TResponse> responseObserver,
        Function<Single<TRequest>, Flowable<TResponse>> delegate) {
    try {
        Single<TRequest> rxRequest = Single.just(request);

        Flowable<TResponse> rxResponse = Preconditions.checkNotNull(delegate.apply(rxRequest));
        rxResponse.subscribe(new ReactivePublisherBackpressureOnReadyHandler<TResponse>(
                (ServerCallStreamObserver<TResponse>) responseObserver));
    } catch (Throwable throwable) {
        responseObserver.onError(prepareError(throwable));
    }
}
 
Example 25
Project: black-mirror   File: NewsDataSource.java   View source code 5 votes vote down vote up
/**
 * @return Zwraca model wiadomości dla kanału TVN24.
 */
@Override
public Single<List<News>> getTvnNews() {
    return tvn24Rss.getNews()
            .map(new Function<Tvn24News, List<News>>() {
                @Override
                public List<News> apply(Tvn24News tvn24News) throws Exception {
                    return tvn24News.channel.news;
                }
            });
}
 
Example 26
Project: Phoenix-for-VK   File: IVideoService.java   View source code 5 votes vote down vote up
@FormUrlEncoded
@POST("video.get")
Single<BaseResponse<Items<VKApiVideo>>> get(@Field("owner_id") Integer ownerId,
                                            @Field("videos") String videos,
                                            @Field("album_id") Integer albumId,
                                            @Field("count") Integer count,
                                            @Field("offset") Integer offset,
                                            @Field("extended") Integer extended);
 
Example 27
Project: dztools   File: StopLoss.java   View source code 5 votes vote down vote up
public Single<Double> forSubmit(final Instrument instrument,
                                final BrokerBuyData brokerBuyData) {
    return Single
        .fromCallable(brokerBuyData::slDistance)
        .flatMap(slDistance -> isDistanceForNoSL(slDistance)
                ? Single.just(StrategyUtil.platformSettings.noSLPrice())
                : forSubmitWithRealDistance(instrument, brokerBuyData));
}
 
Example 28
Project: Phoenix-for-VK   File: AudioApi.java   View source code 5 votes vote down vote up
@Override
public Single<int[]> setBroadcast(IdPair audio, Collection<Integer> targetIds) {
    String audioStr = Objects.isNull(audio) ? null : audio.ownerId + "_" + audio.id;
    return provideService(IAudioService.class)
            .flatMap(service -> service
                    .setBroadcast(audioStr, join(targetIds, ","))
                    .map(extractResponseWithErrorHandling()));

}
 
Example 29
Project: pact-workshop-android   File: PresenterTest.java   View source code 5 votes vote down vote up
@Test
public void should_show_loaded_when_fetch_succeeds() {
  // given
  when(repository.fetchResponse(any())).thenReturn(Single.just(FakeService.RESPONSE));

  // when
  presenter.onStart();

  // then
  verify(view).setViewState(ViewState.Loaded.create(FakeService.RESPONSE.getAnimals()));
}
 
Example 30
Project: Phoenix-for-VK   File: WallApi.java   View source code 5 votes vote down vote up
@Override
public Single<Boolean> delete(Integer ownerId, int postId) {
    return provideService(IWallService.class, TokenType.USER)
            .flatMap(service -> service.delete(ownerId, postId)
                    .map(extractResponseWithErrorHandling())
                    .map(response -> response == 1));
}
 
Example 31
Project: RxLifeCycle   File: UntilLifecycleTransformerSingleTest.java   View source code 5 votes vote down vote up
@Test
public void noEvent() {
    TestObserver<String> testObserver = Single.just("1")
        .delay(1, TimeUnit.MILLISECONDS, testScheduler)
        .compose(RxLifecycle.<String, String>bind(lifecycle))
        .test();

    testObserver.assertNoValues();

    testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS);
    testObserver.assertValue("1");
    testObserver.assertComplete();
}
 
Example 32
Project: Phoenix-for-VK   File: VkRetrofitProvider.java   View source code 5 votes vote down vote up
@Override
public Single<RetrofitWrapper> provideCustomRetrofit(int accountId, String token) {
    return Single.fromCallable(() -> {
        OkHttpClient client = clientFactory.createCustomVkHttpClient(accountId, token, VKGSON, proxyManager.getActiveProxy());
        return createDefaultVkApiRetrofit(client);
    });
}
 
Example 33
Project: dztools   File: BrokerBuy.java   View source code 5 votes vote down vote up
public Single<Integer> openTrade(final BrokerBuyData brokerBuyData) {
    return Single
        .defer(() -> tradeUtility.instrumentForTrading(brokerBuyData.assetName()))
        .flatMap(instrument -> submitParamsRunner.get(instrument, brokerBuyData))
        .flatMap(order -> processOrderAndGetResult(order, brokerBuyData))
        .onErrorReturnItem(ZorroReturnValues.BROKER_BUY_FAIL.getValue());
}
 
Example 34
Project: AndroidSensors   File: GPSSensorGatheringTest.java   View source code 5 votes vote down vote up
private Single<Long> gatherDuring10Sec(GathererCreator gathererCreator) {
    return gathererCreator.create().recordStream()
            .subscribeOn(Schedulers.newThread())
            .take(10, TimeUnit.SECONDS)
            .toObservable()
            .count();
}
 
Example 35
Project: NovelReader   File: ReviewDetailPresenter.java   View source code 5 votes vote down vote up
@Override
public void refreshReviewDetail(String detailId, int start, int limit) {
    Single<ReviewDetailBean> detailSingle = RemoteRepository
            .getInstance().getReviewDetail(detailId);

    Single<List<CommentBean>> bestCommentsSingle = RemoteRepository
            .getInstance().getBestComments(detailId);

    Single<List<CommentBean>> commentsSingle = RemoteRepository
            .getInstance().getDetailBookComments(detailId, start, limit);

    Disposable detailDispo = RxUtils.toCommentDetail(detailSingle, bestCommentsSingle, commentsSingle)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (bean) -> {
                        mView.finishRefresh(bean.getDetail(),
                                bean.getBestComments(), bean.getComments());
                        mView.complete();
                    },
                    (e) -> {
                        mView.showError();
                        LogUtils.e(e);
                    }
            );
    addDisposable(detailDispo);
}
 
Example 36
Project: Phoenix-for-VK   File: IGroupsApi.java   View source code 4 votes vote down vote up
@CheckResult
Single<Boolean> join(int groupId, Integer notSure);
 
Example 37
Project: dztools   File: TickTimeProviderTest.java   View source code 4 votes vote down vote up
private OngoingStubbing<Single<Long>> stubGetLatestFromRepository() {
    return when(tickTimeRepositoryMock.get());
}
 
Example 38
Project: vertx-musicstore   File: ArtistHandler.java   View source code 4 votes vote down vote up
private Single<JsonObject> findArtist(SQLConnection sqlConnection, Long artistId) {
  return sqlConnection.rxQueryStreamWithParams(findArtistById, new JsonArray().add(artistId))
    .flatMapObservable(SQLRowStream::toObservable)
    .map(row -> new JsonObject().put("id", artistId).put("name", row.getString(0)))
    .singleOrError();
}
 
Example 39
Project: android-mvp-architecture   File: AppDataManager.java   View source code 4 votes vote down vote up
@Override
public Single<LoginResponse> doServerLoginApiCall(LoginRequest.ServerLoginRequest
                                                          request) {
    return mApiHelper.doServerLoginApiCall(request);
}
 
Example 40
Project: REDAndroid   File: DataManager.java   View source code 4 votes vote down vote up
public Single<TorrentSearch> torrentSearch(String term) {
    return mApiService.torrentSearch(term);
}