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

The following examples show how to use io.reactivex.Observable#create() . 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: Subscription.java    From dive-into-graphql-in-java with GNU General Public License v3.0 6 votes vote down vote up
public Publisher<Score> talkScores(final String title) {
    Observable<Score> observable = Observable.create(e -> {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> {
            Score s = Score.builder()
                           .title(title)
                           .score(Integer.valueOf((int) Math.floor(Math.random()*10)))
                           .build();
            e.onNext(s);
        }, 0, 2, TimeUnit.SECONDS);
    });

    ConnectableObservable connectableObservable = observable.share().publish();
    connectableObservable.connect();
    return connectableObservable.toFlowable(BackpressureStrategy.BUFFER);
}
 
Example 2
Source File: RxPermissions.java    From RuntimePermission with Apache License 2.0 6 votes vote down vote up
public Observable<PermissionResult> request(final List<String> permissions) {
    return Observable.create(new ObservableOnSubscribe<PermissionResult>() {
        @Override
        public void subscribe(final ObservableEmitter<PermissionResult> emitter) throws Exception {
            runtimePermission
                    .request(permissions)
                    .onResponse(new ResponseCallback() {
                        @Override
                        public void onResponse(PermissionResult result) {
                            if (result.isAccepted()) {
                                emitter.onNext(result);
                                emitter.onComplete();
                            } else {
                                emitter.onError(new Error(result));
                            }
                        }
                    }).ask();
        }
    });
}
 
Example 3
Source File: ExampleUnitTest.java    From RxAndroid-Sample with Apache License 2.0 6 votes vote down vote up
private Observable<Integer> getOriginalObservable() {
    final List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6);

    return Observable
            .create(new ObservableOnSubscribe<Integer>() {
                @Override
                public void subscribe(ObservableEmitter<Integer> emitter) {
                    for (Integer integer : integers) {

                        if (!emitter.isDisposed()) {
                            emitter.onNext(integer);
                        }
                    }

                    if (!emitter.isDisposed()) {
                        emitter.onComplete();
                    }
                }

            });
}
 
Example 4
Source File: Demo_MultipleSubscribers.java    From Reactive-Programming-With-Java-9 with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May"};
	List<String> months = Arrays.asList(monthArray);

	Observable<Object> observable = Observable.create(subscriber -> {
		try {
			System.out.println("creating ");
			for (String data : months) {
				subscriber.onNext(data);
			}
			subscriber.onComplete();
		} catch (Exception e) {
			// TODO: handle exception
			subscriber.onError(e);
		}
	});
	observable.subscribe(item -> System.out.println("month:-" + item));
	observable.subscribe(item -> System.out.println("month:-" + item));

}
 
Example 5
Source File: DiskDataSource.java    From RxJava2-Android-Samples with Apache License 2.0 5 votes vote down vote up
public Observable<Data> getData() {
    return Observable.create(emitter -> {
        if (data != null) {
            emitter.onNext(data);
        }
        emitter.onComplete();
    });
}
 
Example 6
Source File: RxContacts.java    From MultiContactPicker with Apache License 2.0 5 votes vote down vote up
public static Observable<Contact> fetch (@NonNull final LimitColumn columnLimitChoice, @NonNull final Context context) {
    return Observable.create(new ObservableOnSubscribe<Contact>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<Contact> e) throws Exception {
            new RxContacts(context).fetch(columnLimitChoice, e);
        }
    });
}
 
Example 7
Source File: Demo_Cold_Observable.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
public static void main(String[] args) {

		Observable observable = Observable.create(observer -> {
			observer.onNext("I am Hot Observable " + Math.random()*100);
			observer.onComplete();
		});

		observable.subscribe(consumer -> System.out.println("message:-" + consumer));
		observable.subscribe(consumer -> System.out.println("message:-" + consumer));
	}
 
Example 8
Source File: Code8.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
private static Observable<String> getFileNames() {
    return Observable.create(emitter -> {
        Files.walkFileTree(DIRECTORY,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attr) {
                    // ...
                    return FileVisitResult.CONTINUE;
                }
            });
        // ...
    });
}
 
Example 9
Source File: RegisterModelImpl.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<String> uploadAvatar(String imgPath) {
    return Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
            e.onNext("http://p2.wmpic.me/article/2015/04/15/1429062874_HiUlpSXT.jpeg");
            e.onComplete();
        }
    });
}
 
Example 10
Source File: RxProcess.java    From RxShell with Apache License 2.0 5 votes vote down vote up
public RxProcess(ProcessFactory processFactory, ProcessKiller processKiller, String... commands) {
    this.processCreator = Observable.create(e -> {
        final Process process = processFactory.start(commands);
        e.setCancellable(() -> {
            if (RXSDebug.isDebug()) Timber.tag(TAG).v("cancel()");
            processKiller.kill(process);
        });
        e.onNext(process);
        process.waitFor();
        e.onComplete();
    });
}
 
Example 11
Source File: RxCache.java    From RxEasyHttp with Apache License 2.0 5 votes vote down vote up
/**
 * 保存
 *
 * @param key   缓存key
 * @param value 缓存Value
 */
public <T> Observable<Boolean> save(final String key, final T value) {
    return Observable.create(new SimpleSubscribe<Boolean>() {
        @Override
        Boolean execute() throws Throwable {
            cacheCore.save(key, value);
            return true;
        }
    });
}
 
Example 12
Source File: RxCache.java    From RxEasyHttp with Apache License 2.0 5 votes vote down vote up
/**
 * 根据时间读取缓存
 *
 * @param type 保存的类型
 * @param key  缓存key
 * @param time 保存时间
 */
public <T> Observable<T> load(final Type type, final String key, final long time) {
    return Observable.create(new SimpleSubscribe<T>() {
        @Override
        T execute() {
            return cacheCore.load(type, key, time);
        }
    });
}
 
Example 13
Source File: MainActivity.java    From RxJavaPriorityScheduler with Apache License 2.0 5 votes vote down vote up
private Observable<String> getObservable(final String value) {
    return Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            // simulate long task
            Thread.sleep(3000);
            emitter.onNext(value);
            emitter.onComplete();
        }
    });
}
 
Example 14
Source File: UserProfilePresenter.java    From Capstone-Project with MIT License 5 votes vote down vote up
@Override
public void getWebsite(final int userId) {
    Observable<String> observableWebsite = Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            String website = PredatorDatabase.getInstance()
                    .getWebsiteForUser(userId);
            if (!TextUtils.isEmpty(website)) {
                emitter.onNext(website);
            } else {
                emitter.onError(new NullPointerException("No website available for this user."));
            }
            emitter.onComplete();
        }
    });

    observableWebsite.subscribeOn(Schedulers.io());
    observableWebsite.observeOn(AndroidSchedulers.mainThread());

    mCompositeDisposable.add(observableWebsite.subscribeWith(new DisposableObserver<String>(){
        @Override
        public void onNext(String value) {
            Logger.d("onNext: getWebsite: " + value);
            mView.websiteAvailable(value);
        }

        @Override
        public void onError(Throwable e) {
            Logger.e(TAG, "onError: " + e.getMessage(), e);
            mView.websiteUnavailable();
        }

        @Override
        public void onComplete() {
            Logger.d(TAG, "onComplete: fetched user website");
        }
    }));
}
 
Example 15
Source File: RxSharedPreferences.java    From RxSharedPreferences with Apache License 2.0 5 votes vote down vote up
public Observable<Boolean> getBoolean(final String key, final boolean defaultValue) {
    return Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {
            e.onNext(sharedPreferences.getBoolean(key, defaultValue));
            e.onComplete();
        }
    });
}
 
Example 16
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 17
Source File: BookContent.java    From MyBookshelf with GNU General Public License v3.0 4 votes vote down vote up
Observable<BookContentBean> analyzeBookContent(final String s, final BaseChapterBean chapterBean, final BaseChapterBean nextChapterBean, BookShelfBean bookShelfBean, Map<String, String> headerMap) {
    return Observable.create(e -> {
        if (TextUtils.isEmpty(s)) {
            e.onError(new Throwable(MApplication.getInstance().getString(R.string.get_content_error) + chapterBean.getDurChapterUrl()));
            return;
        }
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = NetworkUtils.getAbsoluteURL(bookShelfBean.getBookInfoBean().getChapterUrl(), chapterBean.getDurChapterUrl());
        }
        if (StringUtils.isJsonType(s) && !MApplication.getInstance().getDonateHb()) {
            e.onError(new VipThrowable());
            e.onComplete();
            return;
        }
        Debug.printLog(tag, "┌成功获取正文页");
        Debug.printLog(tag, "└" + baseUrl);
        BookContentBean bookContentBean = new BookContentBean();
        bookContentBean.setDurChapterIndex(chapterBean.getDurChapterIndex());
        bookContentBean.setDurChapterUrl(chapterBean.getDurChapterUrl());
        bookContentBean.setTag(tag);
        AnalyzeRule analyzer = new AnalyzeRule(bookShelfBean);
        WebContentBean webContentBean = analyzeBookContent(analyzer, s, chapterBean.getDurChapterUrl(), baseUrl);
        bookContentBean.setDurChapterContent(webContentBean.content);

        /*
         * 处理分页
         */
        if (!TextUtils.isEmpty(webContentBean.nextUrl)) {
            List<String> usedUrlList = new ArrayList<>();
            usedUrlList.add(chapterBean.getDurChapterUrl());
            BaseChapterBean nextChapter;
            if (nextChapterBean != null) {
                nextChapter = nextChapterBean;
            } else {
                nextChapter = DbHelper.getDaoSession().getBookChapterBeanDao().queryBuilder()
                        .where(BookChapterBeanDao.Properties.NoteUrl.eq(chapterBean.getNoteUrl()),
                                BookChapterBeanDao.Properties.DurChapterIndex.eq(chapterBean.getDurChapterIndex() + 1))
                        .build().unique();
            }

            while (!TextUtils.isEmpty(webContentBean.nextUrl) && !usedUrlList.contains(webContentBean.nextUrl)) {
                usedUrlList.add(webContentBean.nextUrl);
                if (nextChapter != null && NetworkUtils.getAbsoluteURL(baseUrl, webContentBean.nextUrl).equals(NetworkUtils.getAbsoluteURL(baseUrl, nextChapter.getDurChapterUrl()))) {
                    break;
                }
                AnalyzeUrl analyzeUrl = new AnalyzeUrl(webContentBean.nextUrl, headerMap, tag);
                try {
                    String body;
                    Response<String> response = BaseModelImpl.getInstance().getResponseO(analyzeUrl).blockingFirst();
                    body = response.body();
                    webContentBean = analyzeBookContent(analyzer, body, webContentBean.nextUrl, baseUrl);
                    if (!TextUtils.isEmpty(webContentBean.content)) {
                        bookContentBean.setDurChapterContent(bookContentBean.getDurChapterContent() + "\n" + webContentBean.content);
                    }
                } catch (Exception exception) {
                    if (!e.isDisposed()) {
                        e.onError(exception);
                    }
                }
            }
        }
        e.onNext(bookContentBean);
        e.onComplete();
    });
}
 
Example 18
Source File: BookContent.java    From a with GNU General Public License v3.0 4 votes vote down vote up
Observable<BookContentBean> analyzeBookContent(final String s, final BaseChapterBean chapterBean, final BaseChapterBean nextChapterBean, BookShelfBean bookShelfBean, Map<String, String> headerMap) {
    return Observable.create(e -> {
        if (TextUtils.isEmpty(s)) {
            e.onError(new Throwable(MApplication.getInstance().getString(R.string.get_content_error) + chapterBean.getDurChapterUrl()));
            return;
        }
        if (TextUtils.isEmpty(baseUrl)) {
            baseUrl = NetworkUtils.getAbsoluteURL(bookShelfBean.getBookInfoBean().getChapterUrl(), chapterBean.getDurChapterUrl());
        }
        //if (StringUtils.isJsonType(s) && !MApplication.getInstance().getDonateHb()) {
        //    e.onError(new Throwable(MApplication.getInstance().getString(R.string.donate_s)));
        //    e.onComplete();
        //    return;
        //}
        Debug.printLog(tag, "┌成功获取正文页");
        Debug.printLog(tag, "└" + baseUrl);
        BookContentBean bookContentBean = new BookContentBean();
        bookContentBean.setDurChapterIndex(chapterBean.getDurChapterIndex());
        bookContentBean.setDurChapterUrl(chapterBean.getDurChapterUrl());
        bookContentBean.setTag(tag);
        AnalyzeRule analyzer = new AnalyzeRule(bookShelfBean);
        WebContentBean webContentBean = analyzeBookContent(analyzer, s, chapterBean.getDurChapterUrl(), baseUrl);
        bookContentBean.setDurChapterContent(webContentBean.content);

        /*
         * 处理分页
         */
        if (!TextUtils.isEmpty(webContentBean.nextUrl)) {
            List<String> usedUrlList = new ArrayList<>();
            usedUrlList.add(chapterBean.getDurChapterUrl());
            BaseChapterBean nextChapter;
            if (nextChapterBean != null) {
                nextChapter = nextChapterBean;
            } else {
                nextChapter = DbHelper.getDaoSession().getBookChapterBeanDao().queryBuilder()
                        .where(BookChapterBeanDao.Properties.NoteUrl.eq(chapterBean.getNoteUrl()),
                                BookChapterBeanDao.Properties.DurChapterIndex.eq(chapterBean.getDurChapterIndex() + 1))
                        .build().unique();
            }

            while (!TextUtils.isEmpty(webContentBean.nextUrl) && !usedUrlList.contains(webContentBean.nextUrl)) {
                usedUrlList.add(webContentBean.nextUrl);
                if (nextChapter != null && NetworkUtils.getAbsoluteURL(baseUrl, webContentBean.nextUrl).equals(NetworkUtils.getAbsoluteURL(baseUrl, nextChapter.getDurChapterUrl()))) {
                    break;
                }
                AnalyzeUrl analyzeUrl = new AnalyzeUrl(webContentBean.nextUrl, headerMap, tag);
                try {
                    String body;
                    Response<String> response = BaseModelImpl.getInstance().getResponseO(analyzeUrl).blockingFirst();
                    body = response.body();
                    webContentBean = analyzeBookContent(analyzer, body, webContentBean.nextUrl, baseUrl);
                    if (!TextUtils.isEmpty(webContentBean.content)) {
                        bookContentBean.setDurChapterContent(bookContentBean.getDurChapterContent() + "\n" + webContentBean.content);
                    }
                } catch (Exception exception) {
                    if (!e.isDisposed()) {
                        e.onError(exception);
                    }
                }
            }
        }
        e.onNext(bookContentBean);
        e.onComplete();
    });
}
 
Example 19
Source File: RxFirebaseDatabase.java    From rxfirebase with Apache License 2.0 4 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Observable<ChildEvent> childEvents(@NonNull final Query query) {
    return Observable.create(new QueryChildEventsOnSubscribe(query));
}
 
Example 20
Source File: StockTickerPublisher.java    From graphql-java-subscription-example with MIT License 3 votes vote down vote up
public StockTickerPublisher() {
    Observable<StockPriceUpdate> stockPriceUpdateObservable = Observable.create(emitter -> {

        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(newStockTick(emitter), 0, 2, TimeUnit.SECONDS);

    });

    ConnectableObservable<StockPriceUpdate> connectableObservable = stockPriceUpdateObservable.share().publish();
    connectableObservable.connect();

    publisher = connectableObservable.toFlowable(BackpressureStrategy.BUFFER);
}