public Observable<Void> register() { return Observable.defer( new Func0<Observable<String>>() { @Override public Observable<String> call() { String regId = getRegId(); if (regId != null) { return Observable.just(regId); } else { try { regId = googleCloudMessaging.register( context.getString(R.string.google_project_id)); return Observable.just(regId); } catch (IOException ioe) { return Observable.error(ioe); } } } }) .retry(3) .flatMap( new Func1<String, Observable<Void>>() { @Override public Observable<Void> call(String gcmId) { storeRegId(gcmId); return Observable.just(null); } }); }
public static void main(String... args) { // initialize DiscoveryAndLoadBalancer.getFactory(); // hystrix stream => http://localhost:9999 startHystrixMetricsStream(); System.out.println("Server => Starting at http://localhost:8080/"); System.out.println(" Sample URLs: "); System.out.println(" - http://localhost:8080/device/home?userId=123"); System.out.println("----------------------------------------------------------------"); // start web services => http://localhost:8080 RxNetty.createHttpServer( 8080, (request, response) -> { if (request.getPath().contains("favicon.ico")) { return Observable.empty(); } // System.out.println("Server => Request: " + request.getPath()); return Observable.defer( () -> { HystrixRequestContext.initializeContext(); try { return handleRoutes(request, response); } catch (Throwable e) { System.err.println("Server => Error [" + request.getPath() + "] => " + e); response.setStatus(HttpResponseStatus.BAD_REQUEST); return response.writeStringAndFlush( "Error 500: Bad Request\n" + e.getMessage() + "\n"); } }) .onErrorResumeNext( error -> { System.err.println("Server => Error: " + error.getMessage()); error.printStackTrace(); return writeError(request, response, "Failed: " + error.getMessage()); }) .doOnTerminate( () -> { if (HystrixRequestContext.isCurrentThreadInitialized()) { System.out.println( "Server => Request [" + request.getPath() + "] => " + HystrixRequestLog.getCurrentRequest() .getExecutedCommandsAsString()); HystrixRequestContext.getContextForCurrentThread().shutdown(); } else { System.err.println( "HystrixRequestContext not initialized for thread: " + Thread.currentThread()); } response.close(); }); }) .startAndWait(); }
@Override public Observable<Boolean> publishMessage(List<MessageEntity> messageEntities) { return Observable.defer( () -> { boolean status = true; mTweetMessage.tweetMessages(mMessageDataMapper.unmap(messageEntities)); status = mPostMessage.postMessage(mMessageDataMapper.unmap(messageEntities)); return Observable.just(status); }); }
public Observable<List<Item>> getEmulateResponse(int offset, int limit) { if (offset == OFFSET_WHEN_FAKE_ERROR && fakeErrorCount < MAX_FAKE_ERROR_COUNT) { // emulate fake error in response fakeErrorCount++; return Observable.error(new RuntimeException("fake error")); } else { return Observable.defer(() -> Observable.just(getFakeItemList(offset, limit))) .delaySubscription(FAKE_RESPONSE_TIME_IN_MS, TimeUnit.MILLISECONDS); } }
private void checkCredentials(final String username, final String password) { final String nam = StringUtils.defaultString(username); final String pwd = StringUtils.defaultString(password); if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { ActivityMixin.showToast(this, R.string.err_missing_auth); return; } final Credentials credentials = new Credentials(nam, pwd); final AbstractCredentialsAuthorizationActivity authorizationActivity = this; final ProgressDialog loginDialog = ProgressDialog.show( authorizationActivity, res.getString(R.string.init_login_popup), getAuthDialogWait(), true); loginDialog.setCancelable(false); AppObservable.bindActivity( authorizationActivity, Observable.defer( new Func0<Observable<StatusCode>>() { @Override public Observable<StatusCode> call() { return Observable.just(checkCredentials(credentials)); } })) .subscribeOn(AndroidRxUtils.networkScheduler) .subscribe( new Action1<StatusCode>() { @Override public void call(StatusCode statusCode) { loginDialog.dismiss(); if (statusCode == StatusCode.NO_ERROR) { setCredentials(credentials); showToast(getAuthDialogCompleted()); setResult(RESULT_OK); finish(); } else { Dialogs.message( authorizationActivity, R.string.init_login_popup, res.getString( R.string.init_login_popup_failed_reason, statusCode.getErrorString(res))); checkButton.setText(getAuthCheckAgain()); checkButton.setOnClickListener(new CheckListener()); checkButton.setEnabled(true); } } }); }
@Override public Observable<List<MessageEntity>> importMessage() { return Observable.defer( () -> { ProcessSms processSms = mPostMessage.getProcessSms(); List<SmsMessage> smsMessages = processSms.importMessages(); List<Message> messages = new ArrayList<>(); for (SmsMessage smsMessage : smsMessages) { messages.add(mPostMessage.map(smsMessage)); } return Observable.just(mMessageDataMapper.map(messages)); }); }
/** * Provides list of resources on the basis of search criteria * * @return list of jobs */ @NotNull public Observable<List<Resource>> nextLookup() { return Observable.defer( new Func0<Observable<List<Resource>>>() { @Override public Observable<List<Resource>> call() { try { List<Resource> result = mSyncDelegate.nextLookup(); return Observable.just(result); } catch (ServiceException e) { return Observable.error(e); } } }); }
static Observable<String> sampleObservable() { return Observable.defer( new Func0<Observable<String>>() { @Override public Observable<String> call() { try { // Do some long running operation Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } catch (InterruptedException e) { throw OnErrorThrowable.from(e); } Log.d(TAG, "The sleep is over, now produce something"); return Observable.just("one", "two", "three", "four", "five"); } }); }
public Observable<List<Station>> getStations() { if (stationCache.getStations().isPresent()) { return Observable.just(sortStations(stationCache.getStations().get().values())); } else { return Observable.defer( new Func0<Observable<List<Station>>>() { @Override public Observable<List<Station>> call() { // download stations Map<String, List<Station.Builder>> builderMap = new HashMap<>(); String startId = null; Data data; do { // iterate over ODS cursor data = dataApi.getObjectsSynchronously( PEGEL_ALARM_SOURCE_ID, startId, QUERY_COUNT, PROPERTY_FILTER_STATION); for (JsonNode node : data.getResult()) { Pair<String, Station.Builder> pair = parseStation(node); List<Station.Builder> stationsList = builderMap.get(pair.first); if (stationsList == null) { stationsList = new ArrayList<>(); builderMap.put(pair.first, stationsList); } stationsList.add(pair.second); } startId = data.getCursor().getNext(); } while (data.getCursor().getHasNext()); // count stations per water and build stations Map<String, Station> stations = new HashMap<>(); for (String waterName : builderMap.keySet()) { BodyOfWater water = new BodyOfWater(waterName, builderMap.get(waterName).size()); for (Station.Builder builder : builderMap.get(waterName)) { Station station = builder.setBodyOfWater(water).build(); stations.put(station.getGaugeId(), station); } } stationCache.setStations(stations); return Observable.just(sortStations(stations.values())); } }); } }
protected RollingDistributionStream( final HystrixEventStream<Event> stream, final int numBuckets, final int bucketSizeInMs, final Func2<Histogram, Event, Histogram> addValuesToBucket) { final List<Histogram> emptyDistributionsToStart = new ArrayList<Histogram>(); for (int i = 0; i < numBuckets; i++) { emptyDistributionsToStart.add(CachedValuesHistogram.getNewHistogram()); } final Func1<Observable<Event>, Observable<Histogram>> reduceBucketToSingleDistribution = new Func1<Observable<Event>, Observable<Histogram>>() { @Override public Observable<Histogram> call(Observable<Event> bucket) { return bucket.reduce(CachedValuesHistogram.getNewHistogram(), addValuesToBucket); } }; rollingDistributionStream = Observable.defer( new Func0<Observable<CachedValuesHistogram>>() { @Override public Observable<CachedValuesHistogram> call() { return stream .observe() .window( bucketSizeInMs, TimeUnit.MILLISECONDS) // stream of unaggregated buckets .flatMap( reduceBucketToSingleDistribution) // stream of aggregated Histograms .startWith( emptyDistributionsToStart) // stream of aggregated Histograms that // starts with n empty .window( numBuckets, 1) // windowed stream: each OnNext is a stream of n Histograms .flatMap( reduceWindowToSingleDistribution) // reduced stream: each OnNext is a // single Histogram .map(cacheHistogramValues); // convert to CachedValueHistogram // (commonly-accessed values are cached) } }) .share(); // multicast }
public Observable<Void> unregister() { return Observable.defer( new Func0<Observable<Response>>() { @Override public Observable<Response> call() { try { clearRegId(); googleCloudMessaging.unregister(); return Observable.just(null); } catch (IOException ioe) { return Observable.error(ioe); } } }) .flatMap( new Func1<Response, Observable<Void>>() { @Override public Observable<Void> call(Response response) { return Observable.just(null); } }); }
@Test public void test() { // System.out.println(Arrays.toString(DataType.class.getGenericInterfaces())); Observable<String> observableHello = Observable.just(helloWorld()); Observable<String> observable = Observable.create( new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("ddddd"); subscriber.onCompleted(); } }) .filter(b -> b.startsWith("ddd")) .doOnCompleted( () -> { System.out.println("doOnComplete"); }) // .concatWith(observableHello) // .mergeWith(observableHello) // .mergeWith(observableHello) .ambWith(observableHello); // observable.subscribe(); // Subscription subscription = observable.subscribe(s -> { // System.out.println(s); // }, a->{}, () -> System.out.println("oncomplete")); Observable.defer( () -> Observable.create( subscriber1 -> { System.out.println("deeee"); subscriber1.onCompleted(); })) .subscribe(); }
// Caches are loaded from disk on a computation scheduler to avoid using more threads than cores // while decoding // the image. Downloads happen on downloadScheduler, in parallel with image decoding. private Observable<BitmapDrawable> fetchDrawableUncached(final String url) { if (StringUtils.isBlank(url) || ImageUtils.containsPattern(url, BLOCKED)) { return Observable.just(ImageUtils.getTransparent1x1Drawable(resources)); } // Explicit local file URLs are loaded from the filesystem regardless of their age. The IO part // is short // enough to make the whole operation on the computation scheduler. if (FileUtils.isFileUrl(url)) { return Observable.defer( new Func0<Observable<BitmapDrawable>>() { @Override public Observable<BitmapDrawable> call() { final Bitmap bitmap = loadCachedImage(FileUtils.urlToFile(url), true).left; return bitmap != null ? Observable.just(ImageUtils.scaleBitmapToFitDisplay(bitmap)) : Observable.<BitmapDrawable>empty(); } }) .subscribeOn(AndroidRxUtils.computationScheduler); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? SHARED : geocode; return Observable.create( new OnSubscribe<BitmapDrawable>() { @Override public void call(final Subscriber<? super BitmapDrawable> subscriber) { subscription.add(subscriber); subscriber.add( AndroidRxUtils.computationScheduler .createWorker() .schedule( new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable bitmap = loaded.left; if (loaded.right) { subscriber.onNext(bitmap); subscriber.onCompleted(); return; } if (bitmap != null && !onlySave) { subscriber.onNext(bitmap); } AndroidRxUtils.networkScheduler .createWorker() .schedule( new Action0() { @Override public void call() { downloadAndSave(subscriber); } }); } })); } private ImmutablePair<BitmapDrawable, Boolean> loadFromDisk() { final ImmutablePair<Bitmap, Boolean> loadResult = loadImageFromStorage(url, pseudoGeocode, shared); return scaleImage(loadResult); } private void downloadAndSave(final Subscriber<? super BitmapDrawable> subscriber) { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); if (url.startsWith("data:image/")) { if (url.contains(";base64,")) { ImageUtils.decodeBase64ToFile(StringUtils.substringAfter(url, ";base64,"), file); } else { Log.e("HtmlImage.getDrawable: unable to decode non-base64 inline image"); subscriber.onCompleted(); return; } } else if (subscriber.isUnsubscribed() || downloadOrRefreshCopy(url, file)) { // The existing copy was fresh enough or we were unsubscribed earlier. subscriber.onCompleted(); return; } if (onlySave) { subscriber.onCompleted(); return; } AndroidRxUtils.computationScheduler .createWorker() .schedule( new Action0() { @Override public void call() { final ImmutablePair<BitmapDrawable, Boolean> loaded = loadFromDisk(); final BitmapDrawable image = loaded.left; if (image != null) { subscriber.onNext(image); } else { subscriber.onNext( returnErrorImage ? new BitmapDrawable( resources, BitmapFactory.decodeResource( resources, R.drawable.image_not_loaded)) : ImageUtils.getTransparent1x1Drawable(resources)); } subscriber.onCompleted(); } }); } }); }
private Observable<Long> DeferObserver() { return Observable.defer(() -> Observable.just(System.currentTimeMillis())); }
@NonNull public Observable<List<PostAndImage>> retrieve() { final long currentSavedTimestamp = mUserStorage.getTimestamp(); return Observable.defer( new Func0<Observable<List<PostAndImage>>>() { @Override public Observable<List<PostAndImage>> call() { String subreddits = mUserStorage.getSubreddits(); if (StringUtils.isEmpty(subreddits)) { subreddits = StringUtils.join("+", Constants.sDefaultSelectedSubreddits); } return mRedditService .latestPosts( subreddits, mUserStorage.getSortType(), mUserStorage.getNumberToRequest()) .lift(LatestPostsRetriever.<Post>flattenList()) .filter( new Func1<Post, Boolean>() { @Override public Boolean call(Post post) { // Check that this post is new (i.e. we haven't retrieved it before) return post.getCreatedUtc() > currentSavedTimestamp; } }) .doOnNext( new Action1<Post>() { @Override public void call(Post post) { // Save the timestamps from these new posts, so we don't see them again mUserStorage.setSeenTimestamp(post.getCreatedUtc()); } }) .flatMap( new Func1<Post, Observable<PostAndImage>>() { @Override public Observable<PostAndImage> call(final Post post) { return Observable.defer( new Func0<Observable<PostAndImage>>() { @Override public Observable<PostAndImage> call() { final PostAndImage postAndImage = new PostAndImage(post); if (post.hasImageUrl()) { final byte[] bytes = mImageDownloader.downloadImage(post.getImageUrl()); if (bytes != null) { postAndImage.setImage(Asset.createFromBytes(bytes)); } } return Observable.just(postAndImage); } }) .onErrorResumeNext( new Func1<Throwable, Observable<PostAndImage>>() { @Override public Observable<PostAndImage> call(Throwable throwable) { // If we fail to download the image, just skip this Post return Observable.empty(); } }); } }) .toList(); } }) .onErrorResumeNext( new Func1<Throwable, Observable<List<PostAndImage>>>() { @Override public Observable<List<PostAndImage>> call(Throwable throwable) { Timber.e(throwable, "Failed to get latest posts"); // If we fail somewhere whilst retrieving posts, just emit an empty list return Observable.just(Collections.<PostAndImage>emptyList()); } }); }
public VideoConversion createVideo(final Face face) { final List<PhotoInfo> photoInfos = photoManager.getPhotosForFace(face); final List<File> photoFiles = Lists.newArrayList(); for (PhotoInfo info : photoInfos) photoFiles.add(info.getPhotoFile()); final File progressFile = new File(getTmpVideoDir(), "progress"); final Observable<File> conversionObservable = Observable.defer( new Func0<Observable<File>>() { @Override public Observable<File> call() { // rename photos to img0000.jpg + process photos Collections.sort(photoFiles); int idx = 0; for (File oldFile : photoFiles) { ++idx; try { // process image Bitmap originalImage = BitmapFactory.decodeFile(oldFile.getAbsolutePath()); Bitmap processedImage = photoProcessor.findFaceAndCrop(originalImage); // store image final File newFile = new File(getTmpVideoDir(), "img" + String.format("%03d", idx) + ".jpg"); if (!newFile.createNewFile()) Timber.e("failed to create file " + newFile.getAbsolutePath()); processedImage.compress( Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(newFile)); } catch (IOException e) { Timber.d(e, "failed to copy + process file"); return Observable.error(e); } } // create conversion command final String photoFileNameTemplate = getTmpVideoDir().getAbsolutePath() + "/img%03d.jpg"; final String videoFileName = VIDEO_DATE_FORMAT.format(new Date()) + ".mp4"; final File videoFile = new File(getExternalFaceVideoDir(face), videoFileName); final String command = String.format( "-progress %s -framerate 1/%d -i %s -c:v libx264 -r %d -pix_fmt yuv420p %s", progressFile.getAbsolutePath(), IMAGE_LENGTH_IN_SECONDS, photoFileNameTemplate, FRAMERATE, videoFile.getAbsolutePath()); Timber.d("executing ffmpeg: " + command); // start command return Observable.create( new Observable.OnSubscribe<File>() { @Override public void call(final Subscriber<? super File> subscriber) { try { fFmpeg.execute( command, new FFmpegExecuteResponseHandler() { @Override public void onSuccess(String s) { Timber.d("video conversion success: " + s); if (subscriber.isUnsubscribed()) return; subscriber.onNext(videoFile); subscriber.onCompleted(); } @Override public void onProgress(String s) { Timber.d("video conversion progress: " + s); } @Override public void onFailure(String s) { Timber.d("video conversion error: " + s); subscriber.onError(new IllegalStateException(s)); } @Override public void onStart() { Timber.d("video conversion started"); } @Override public void onFinish() { Timber.d("video conversion finished"); } }); } catch (FFmpegCommandAlreadyRunningException e) { Timber.e(e, "failed to start video conversion"); if (subscriber.isUnsubscribed()) return; subscriber.onError(e); } } }); } }) .finallyDo( new Action0() { @Override public void call() { // cleanup ioUtils.delete(getTmpVideoDir()); } }); return new VideoConversion(progressFile, photoFiles.size(), conversionObservable); }