rx.schedulers.Schedulers Java Examples

The following examples show how to use rx.schedulers.Schedulers. 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 Project: qiscus-sdk-android   Author: qiscus   File: QiscusComment.java    License: Apache License 2.0 6 votes vote down vote up
public void loadLinkPreviewData() {
    if (getType() == Type.LINK) {
        if (previewData != null) {
            linkPreviewListener.onLinkPreviewReady(this, previewData);
        } else {
            QiscusUrlScraper.getInstance()
                    .generatePreviewData(urls.get(0))
                    .doOnNext(previewData -> previewData.setUrl(urls.get(0)))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(previewData -> {
                        this.previewData = previewData;
                        if (linkPreviewListener != null) {
                            linkPreviewListener.onLinkPreviewReady(this, previewData);
                        }
                    }, Throwable::printStackTrace);
        }
    }
}
 
Example #2
Source Project: RoomBookerMVP   Author: macoscope   File: EventPresenter.java    License: MIT License 6 votes vote down vote up
private void getEvent() {
    fetchEventUsecase.setEventParams(calendarId, eventId);
    eventView.showLoading();
    eventSubscribtion = fetchEventUsecase.execute()
            .subscribeOn(Schedulers.io())

            .onErrorReturn(new Func1<Throwable, Event>() {
                @Override
                public Event call(Throwable throwable) {
                    eventView.showError();
                    return null;
                }
            })
            .subscribe(new Action1<Event>() {
                @Override
                public void call(Event event) {
                    eventView.showEvent(event);
                }
            });
}
 
Example #3
Source Project: qiscus-sdk-android   Author: qiscus   File: QiscusChatPresenter.java    License: Apache License 2.0 6 votes vote down vote up
private void sendComment(QiscusComment qiscusComment) {
    view.onSendingComment(qiscusComment);
    Subscription subscription = QiscusApi.getInstance().sendMessage(qiscusComment)
            .doOnSubscribe(() -> Qiscus.getDataStore().addOrUpdate(qiscusComment))
            .doOnNext(this::commentSuccess)
            .doOnError(throwable -> commentFail(throwable, qiscusComment))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(commentSend -> {
                if (commentSend.getRoomId() == room.getId()) {
                    view.onSuccessSendComment(commentSend);
                }
            }, throwable -> {
                QiscusErrorLogger.print(throwable);
                throwable.printStackTrace();
                if (qiscusComment.getRoomId() == room.getId()) {
                    view.onFailedSendComment(qiscusComment);
                }
            });

    pendingTask.put(qiscusComment, subscription);
}
 
Example #4
Source Project: droidddle   Author: goodev   File: AddToBucketActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onClicked(Bucket data) {
    if (!Utils.hasInternet(this)) {
        Toast.makeText(this, R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    Observable<Response> observable = ApiFactory.getService(this).addShotToBucket(data.id, mShotId);
    observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SucessCallback<Response>(this, R.string.shot_add_to_bucket_success) {
                @Override
                public void call(Response o) {
                    super.call(o);
                    finish();
                }
            }, new ErrorCallback(this));
}
 
Example #5
Source Project: DoingDaily   Author: WangGanxin   File: CommonRemoteDataSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getShowPictures(Map<String, String> options, @NonNull final ShowPictureCallback callback) {
    NetworkManager.getShowAPI().getPictures(options).subscribeOn(Schedulers.newThread())//子线程访问网络
            .observeOn(AndroidSchedulers.mainThread())//回调到主线程
            .subscribe(new Action1<PictureShowBean>() {
                @Override
                public void call(PictureShowBean bean) {
                    callback.onPicturesLoaded(bean);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    callback.onDataNotAvailable();
                }
            });
}
 
Example #6
Source Project: journaldev   Author: journaldev   File: PresenterImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void loadData() {

    mView.showProgress();

    apiInterface.getData("10").subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<CryptoData>>() {
                @Override
                public void onCompleted() {
                    mView.showComplete();
                    mView.hideProgress();
                }

                @Override
                public void onError(Throwable e) {
                    mView.showError("Error occurred");
                    mView.hideProgress();
                }

                @Override
                public void onNext(List<CryptoData> data) {
                    mView.showData(data);
                }
            });
}
 
Example #7
Source Project: RxUploader   Author: jsaund   File: UploaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadFileNotFoundException() throws Exception {
    final File file = new File("invalid");
    final String jobId = "job-id";
     final Job job = Job.builder()
            .setId(jobId)
            .setStatus(Status.createQueued(jobId))
            .setMetadata(Collections.emptyMap())
            .setFilepath("invalid")
            .setMimeType("text/plain")
            .build();

    final UploadService service = mock(UploadService.class);

    final Uploader uploader = new Uploader(service, Schedulers.io());
    final TestSubscriber<Status> ts = TestSubscriber.create();
    uploader.upload(job, file).subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertError(FileNotFoundException.class);
    ts.assertNoValues();
}
 
Example #8
Source Project: code   Author: lastwhispers   File: GetProductInfosCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Observable<ProductInfo> construct() {
    return Observable.create(new Observable.OnSubscribe<ProductInfo>() {
        @Override
        public void call(Subscriber<? super ProductInfo> subscriber) {
            try {
                for (String productId : productIds) {
                    String url = "http://127.0.0.1:8082/getProductInfo?productId=" + productId;
                    String response = HttpClientUtils.sendGetRequest(url);
                    ProductInfo productInfo = JSONObject.parseObject(response, ProductInfo.class);
                    subscriber.onNext(productInfo);
                }
                subscriber.onCompleted();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #9
Source Project: RxPaper   Author: cesarferreira   File: MainActivity.java    License: MIT License 6 votes vote down vote up
public void readCustom(View view) {
	RxPaper.book(mCustomBook)
		.read(PERSON_KEY, defaultValue)
		.subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<Person>() {
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {
				log(e.getMessage());

			}

			@Override
			public void onNext(Person person) {
				log(String.valueOf(person));
			}
		});
}
 
Example #10
Source Project: trading-backtest   Author: lukstei   File: Http.java    License: MIT License 6 votes vote down vote up
public static Observable<HttpResponse> get(String url, Consumer<HttpGet> configureRequest) {
    HttpGet request = new HttpGet(url);
    configureRequest.accept(request);

    return Observable.create(new OnSubscribe<HttpResponse>() {
        @Override public void call(Subscriber<? super HttpResponse> s) {
            try {
                log.debug("GET {}", url);
                s.onNext(getDefaultHttpClient().execute(request));
                s.onCompleted();
            } catch (IOException e) {
                s.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #11
Source Project: BookReader   Author: smuyyh   File: BookDetailPresenter.java    License: Apache License 2.0 6 votes vote down vote up
public void getBookDetail(String bookId) {
    Subscription rxSubscription = bookApi.getBookDetail(bookId).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<BookDetail>() {
                @Override
                public void onNext(BookDetail data) {
                    if (data != null && mView != null) {
                        mView.showBookDetail(data);
                    }
                }

                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: " + e);
                }
            });
    addSubscrebe(rxSubscription);
}
 
Example #12
Source Project: PlayTogether   Author: loserdog-err   File: ChatBll.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 压缩上传
 *
 * @return
 */
public Observable<AVFile> compressImageAndUpload(String path, int maxWidth, int maxHeight)
{
	return compressImage(path, maxWidth, maxHeight)
					.observeOn(Schedulers.io())
					.subscribeOn(Schedulers.computation())
					.flatMap(new Func1<AVFile, Observable<AVFile>>()
					{
						@Override
						public Observable<AVFile> call(AVFile avFile)
						{
							return uploadFile(avFile);
						}
					});


}
 
Example #13
Source Project: RxJava_RxAndroid   Author: zyj1609wz   File: StopActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stop);

    textView = (TextView) findViewById(R.id.textview);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity( new Intent( StopActivity.this , OtherActivity.class));
        }
    });

    //循环发送数字
    Observable.interval(0, 1, TimeUnit.SECONDS)
            .subscribeOn( Schedulers.io())
            .compose(this.<Long>bindUntilEvent(ActivityEvent.STOP ))   //当Activity执行Onstop()方法是解除订阅关系
            .observeOn( AndroidSchedulers.mainThread())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                    System.out.println("lifecycle-stop-" + aLong);
                    textView.setText( "" + aLong );
                }
            });
}
 
Example #14
Source Project: fingerpoetry-android   Author: klisly   File: HomeActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Subscribe
    public void onLoginSuccess(LoginEvent event) {
        Timber.i("receive onLoginSuccess");
        updateNavData();
//        CommonHelper.getTopics(this);
//        CommonHelper.getUserTopics(this);
//        CommonHelper.getSites(this);
//        CommonHelper.getUserSites(this);
        User user = AccountLogic.getInstance().getNowUser();
        if (!user.getIsBasicSet() && Constants.isFirstLaunch()) {
            Constants.setFirstLaunch(false);
            user.setBasicSet(true);
            LoginData data = AccountLogic.getInstance().getLoginData();
            data.setUser(user);
            AccountLogic.getInstance().setLoginData(data);
            AccountApi accountApi = BookRetrofit.getInstance().getAccountApi();
            Map<String, Object> info = new HashMap<>();
            info.put("isBasicSet", user.getIsBasicSet());
            accountApi.update(info, AccountLogic.getInstance().getToken())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(initObserver(HomeActivity.this));
            start(ChooseTopicFragment.newInstance(ChooseTopicFragment.ACTION_SET));
        }
    }
 
Example #15
Source Project: droidddle   Author: goodev   File: NavigationDrawerFragment.java    License: Apache License 2.0 6 votes vote down vote up
public void updateUser(String accessToken) {
    if (mUser != null) {
        return;
    }
    try {
        if (!Utils.hasInternet(getActivity())) {
            return;
        }
        Observable<User> user = ApiFactory.getService(getActivity(), accessToken)
                .getOAuthUser();
        user.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe((u) -> {
                    updateData(u);
                }, new ErrorCallback(getActivity()));
    } catch (Exception e) {
        //TODO have NEP...
        e.printStackTrace();
    }
}
 
Example #16
Source Project: RxFirebase   Author: nmoskalenko   File: RxFirebaseDatabaseTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testObserveSingleWrongType() {

    TestSubscriber<WrongType> testSubscriber = new TestSubscriber<>();
    RxFirebaseDatabase.observeSingleValueEvent(mockDatabase, WrongType.class)
            .subscribeOn(Schedulers.immediate())
            .subscribe(testSubscriber);

    ArgumentCaptor<ValueEventListener> argument = ArgumentCaptor.forClass(ValueEventListener.class);
    verify(mockDatabase).addListenerForSingleValueEvent(argument.capture());
    argument.getValue().onDataChange(mockFirebaseDataSnapshot);

    testSubscriber.assertError(RuntimeException.class);
    testSubscriber.assertNotCompleted();
    testSubscriber.unsubscribe();
}
 
Example #17
Source Project: openwebnet-android   Author: openwebnet   File: ProfileActivity.java    License: MIT License 6 votes vote down vote up
private <T> void requestAction(Func0<Observable<T>> observableAction, Action1<T> onSuccess) {
    hideActions();

    if (utilityService.hasInternetAccess()) {
        observableAction.call()
            // better UX
            .delay(1 , TimeUnit.SECONDS)
            // max http timeout
            .timeout(5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(onSuccess, error -> {
                swipeRefreshLayoutProfile.setRefreshing(false);
                log.error("requestAction: request failed", error);
                showSnackbar(R.string.error_request);
            });
    } else {
        // show empty list
        updateProfiles(Lists.newArrayList());
        // hide
        speedDialProfile.hide();
        log.warn("requestAction: connection unavailable");
        showSnackbar(R.string.error_connection);
    }
}
 
Example #18
Source Project: materialup   Author: goodev   File: PostActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void setupDribbble() {
    commentsList.setAdapter(getLoadingCommentsAdapter());
    if (shot != null && shot.getImageUrl() == null) {
        loaderImage();
    }

    if (mFull) {
        handleContent(shot);
        return;
    }
    if (!Utils.hasInternet(this)) {
        Toast.makeText(this, R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }

    Api.getApiService().getPostSidebar(shot.id)
            .map(muResponse -> JsoupUtil.getPostContent1(shot, muResponse))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(content -> handleContent(content), new ErrorCallback(this));
}
 
Example #19
Source Project: nono-android   Author: tianyuan168326   File: CommunityController.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void postNew(String answerDetail,String questionId){
    ServiceFactory.getPostService().newPost(
            AuthBody.getAuthBodyMap(
                    new Pair<>("access_token", MyApp.getInstance().userInfo.quickAskToken),
                    new Pair<>("user_name", MyApp.getInstance().userInfo.username),
                    new Pair<>("key_detail", answerDetail),
                    new Pair<>("question_id", questionId))
    )
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<WonderFull>() {
                @Override
                public void call(WonderFull wonderFull) {
                    if(wonderFull.state_code ==0){
                        EventBus.getDefault().post(new PostAnswerSuccessEvent());
                    }else{
                        EventBus.getDefault().post(new PostAnswerFailEvent());
                    }
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    EventBus.getDefault().post(new PostAnswerFailEvent());
                }
            });
}
 
Example #20
Source Project: Stock-Hawk   Author: therajanmaurya   File: MainPresenter.java    License: Apache License 2.0 6 votes vote down vote up
public void deleteStock(String symbol) {
    checkViewAttached();
    mSubscriptions.add(mDataManager.deleteStock(symbol)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<Stocks>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "There was an error deleting the stock");
                    getMvpView().showError();
                }

                @Override
                public void onNext(Stocks stock) {
                    showStocks(stock);
                }
            })
    );
}
 
Example #21
Source Project: wear-notify-for-reddit   Author: emmaguy   File: LatestPostsRetrieverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void retrievingSame5PostsTwice_onlyEmitsThemThemFirstTime() {
    updateTimestampWhenSet(1004);

    final List<Post> posts = Arrays.asList(mockPost(1000),
            mockPost(1001),
            mockPost(1002),
            mockPost(1003),
            mockPost(1004));
    when(mRedditService.latestPosts(DEFAULT_SUBREDDIT,
            DEFAULT_SORT,
            DEFAULT_NUMBER)).thenReturn(Observable.just(posts));

    final List<LatestPostsRetriever.PostAndImage> elementsFirstTime = new ArrayList<>();
    mRetriever.retrieve()
            .observeOn(Schedulers.immediate())
            .subscribeOn(Schedulers.immediate())
            .subscribe(elementsFirstTime::addAll);

    verify(mUserStorage).setSeenTimestamp(1004);

    final List<LatestPostsRetriever.PostAndImage> elementsSecondTime = new ArrayList<>();
    mRetriever.retrieve()
            .observeOn(Schedulers.immediate())
            .subscribeOn(Schedulers.immediate())
            .subscribe(elementsSecondTime::addAll);

    verify(mUserStorage, times(0)).setSeenTimestamp(anyInt());

    assertThat(elementsFirstTime.size(), equalTo(5));
    assertThat(elementsSecondTime.size(), equalTo(0));
}
 
Example #22
Source Project: titus-control-plane   Author: Netflix   File: RxJavaComputationSchedulerSensor.java    License: Apache License 2.0 5 votes vote down vote up
private List<WorkerTaskScheduler> findComputationSchedulerWorkers() {
    List<WorkerTaskScheduler> workerTaskSchedulers = new ArrayList<>();
    try {
        int cpuCount = Runtime.getRuntime().availableProcessors();
        Set<Thread> threads = new HashSet<>();
        int iterCount = 0;
        while (workerTaskSchedulers.size() < cpuCount && iterCount < MAX_LOOP_COUNT) {
            iterCount++;

            Worker worker = Schedulers.computation().createWorker();
            AtomicReference<Thread> workerThreadRef = new AtomicReference<>();
            CountDownLatch latch = new CountDownLatch(1);
            worker.schedule(() -> {
                workerThreadRef.set(Thread.currentThread());
                latch.countDown();
            });
            if (!latch.await(MAX_INIT_PROCESSING_WAIT_TIME_MS, TimeUnit.MILLISECONDS)) {
                logger.warn("RxJava computation scheduler sensor initialization error");
                return Collections.emptyList();
            }
            if (threads.add(workerThreadRef.get())) {
                workerTaskSchedulers.add(new WorkerTaskScheduler(workerThreadRef.get(), worker));
            } else {
                worker.unsubscribe();
            }
        }
        return workerTaskSchedulers;
    } catch (Exception e) {
        logger.warn("RxJava computation scheduler sensor initialization error", e);
        workerTaskSchedulers.forEach(WorkerTaskScheduler::shutdown);
        return Collections.emptyList();
    }
}
 
Example #23
Source Project: android   Author: hyperboria   File: MainActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void handleEvent(ApplicationEvents.StopCjdnsService event) {
    Toast.makeText(getApplicationContext(), "Stopping CjdnsService", Toast.LENGTH_SHORT).show();

    // Kill cjdroute process.
    Cjdroute.running(this)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io())
            .subscribe(mCjdroute.terminate());

    stopService(new Intent(getApplicationContext(), CjdnsService.class));
}
 
Example #24
Source Project: akarnokd-misc   Author: akarnokd   File: SingleUnsubscribe.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    Single.fromCallable(() -> 42)
    .subscribeOn(Schedulers.io())
    .observeOn(Schedulers.computation())
    .doOnSubscribe(() -> System.out.println("subscribed"))
    .doOnUnsubscribe(() -> System.out.println("unsubscribed"))
    .subscribe(integer -> System.out.println("got result"));

    Thread.sleep(1000);
}
 
Example #25
Source Project: hawkular-metrics   Author: hawkular   File: StringHandler.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/tags/{tags}/raw")
@ApiOperation(value = "Retrieve string data on multiple metrics by tags.", response = DataPoint.class,
        responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully fetched metric data points."),
        @ApiResponse(code = 204, message = "Query was successful, but no data was found."),
        @ApiResponse(code = 400, message = "No metric ids are specified", response = ApiError.class),
        @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.",
                response = ApiError.class)
})
public void getRawDataByTag(
        @Suspended AsyncResponse asyncResponse,
        @PathParam("tags") String tags,
        @ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") String start,
        @ApiParam(value = "Defaults to now") @QueryParam("end") String end,
        @ApiParam(value = "Use data from earliest received, subject to retention period")
        @QueryParam("fromEarliest") Boolean fromEarliest,
        @ApiParam(value = "Limit the number of data points returned") @QueryParam("limit") Integer limit,
        @ApiParam(value = "Data point sort order, based on timestamp") @QueryParam("order") Order order
) {
    metricsService.findMetricIdentifiersWithFilters(getTenant(), STRING, tags)
            .toList()
            .flatMap(metricIds -> TimeAndSortParams.<String>deferredBuilder(start, end)
                    .fromEarliest(fromEarliest, metricIds, this::findTimeRange)
                    .sortOptions(limit, order)
                    .forString()
                    .toObservable()
                    .flatMap(p -> metricsService.findDataPoints(metricIds, p.getTimeRange().getStart(),
                            p.getTimeRange().getEnd(), p.getLimit(), p.getOrder())
                            .observeOn(Schedulers.io())))
            .subscribe(createNamedDataPointObserver(asyncResponse, STRING));
}
 
Example #26
Source Project: azure-cosmosdb-java   Author: Azure   File: RxGatewayStoreModel.java    License: MIT License 5 votes vote down vote up
/**
 * Given the request it creates an observable which upon subscription issues HTTP call and emits one RxDocumentServiceResponse.
 *
 * @param request
 * @param method
 * @return Observable<RxDocumentServiceResponse>
 */
public Observable<RxDocumentServiceResponse> performRequest(RxDocumentServiceRequest request, HttpMethod method) {

    try {
        URI uri = getUri(request);
        HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.create(method, uri.toString());

        this.fillHttpRequestBaseWithHeaders(request.getHeaders(), httpRequest);

        if (request.getContentObservable() != null) {

            // TODO validate this
            // convert byte[] to ByteBuf
            // why not use Observable<byte[]> directly?
            Observable<ByteBuf> byteBufObservable = request.getContentObservable()
                    .map(bytes ->  Unpooled.wrappedBuffer(bytes));

            httpRequest.withContentSource(byteBufObservable);
        } else if (request.getContent() != null){
            httpRequest.withContent(request.getContent());
        }

        RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort());

        Observable<HttpClientResponse<ByteBuf>> clientResponseObservable = this.httpClient.submit(serverInfo, httpRequest);

        return toDocumentServiceResponse(clientResponseObservable, request).observeOn(Schedulers.computation());

    } catch (Exception e) {
        return Observable.error(e);
    }
}
 
Example #27
Source Project: base_app_android   Author: RefineriaWeb   File: PresenterSubscriptionsTest.java    License: Apache License 2.0 5 votes vote down vote up
private Observable<Object> getExpensiveObservable() {
    return Observable.create(subscriber -> {
        try {
            Thread.sleep(500);
            subscriber.onNext("Mock");
        } catch (InterruptedException e) {}
    }).subscribeOn(Schedulers.newThread());
}
 
Example #28
Source Project: octoandroid   Author: nairbspace   File: UseCase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(Subscriber useCaseSubscriber) {
    unsubscribe();
    mSubscription = buildUseCaseObservable()
            .subscribeOn(Schedulers.from(mThreadExecutor))
            .observeOn(mPostExecutionThread.getScheduler())
            .subscribe(useCaseSubscriber);
}
 
Example #29
Source Project: hawkular-metrics   Author: hawkular   File: GaugeHandler.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/tags/{tags}/raw")
@ApiOperation(value = "Retrieve raw gauge data on multiple metrics by tags.", response = DataPoint.class,
        responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully fetched metric data points."),
        @ApiResponse(code = 204, message = "Query was successful, but no data was found."),
        @ApiResponse(code = 400, message = "No metric ids are specified", response = ApiError.class),
        @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.",
                response = ApiError.class)
})
public void getRawDataByTag(
        @Suspended AsyncResponse asyncResponse,
        @PathParam("tags") String tags,
        @ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") String start,
        @ApiParam(value = "Defaults to now") @QueryParam("end") String end,
        @ApiParam(value = "Use data from earliest received, subject to retention period")
        @QueryParam("fromEarliest") Boolean fromEarliest,
        @ApiParam(value = "Limit the number of data points returned") @QueryParam("limit") Integer limit,
        @ApiParam(value = "Data point sort order, based on timestamp") @QueryParam("order") Order order
) {
    metricsService.findMetricIdentifiersWithFilters(getTenant(), GAUGE, tags)
            .toList()
            .flatMap(metricIds -> TimeAndSortParams.<Double>deferredBuilder(start, end)
                    .fromEarliest(fromEarliest, metricIds, this::findTimeRange)
                    .sortOptions(limit, order)
                    .toObservable()
                    .flatMap(p -> metricsService.findDataPoints(metricIds, p.getTimeRange().getStart(),
                            p.getTimeRange().getEnd(), p.getLimit(), p.getOrder())
                            .observeOn(Schedulers.io())))
            .subscribe(createNamedDataPointObserver(asyncResponse, GAUGE));
}
 
Example #30
Source Project: droidddle   Author: goodev   File: ProjectShotFragment.java    License: Apache License 2.0 5 votes vote down vote up
public void loadData() {
    Observable<List<Shot>> observable = null;
    if (mType == UiUtils.TYPE_PROJECT) {
        observable = ApiFactory.getService(getActivity()).getProjectShots(mId, mCurrentPage);
    } else {
        observable = ApiFactory.getService(getActivity()).getBucketShots(mId, mCurrentPage);
    }
    observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe((data) -> {
        updateData(data);
    }, new ErrorCallback(getActivity()));
}