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

The following are Jave code examples for showing how to use create() of the io.reactivex.Observable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: PXLSRT   File: TempStorageUtils.java   View Source Code Vote up 6 votes
static Observable<Boolean> storeFile(final FileOutputStream fos, final Bitmap bitmap, final int quality) {
    return Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
            bitmap.recycle();
            try {
                fos.flush();
                fos.close();
                emitter.onNext(true);
            } catch (IOException e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }
    });
}
 
Example 2
Project: Reactive-Programming-With-Java-9   File: Demo_MultipleSubscribers.java   View Source Code Vote up 6 votes
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 3
Project: RetroMusicPlayer   File: PlaylistLoader.java   View Source Code Vote up 6 votes
@NonNull
public static Observable<ArrayList<Playlist>> getAllPlaylists(@Nullable final Cursor cursor) {
    return Observable.create(e -> {
        ArrayList<Playlist> playlists = new ArrayList<>();

        if (cursor != null && cursor.moveToFirst()) {
            do {
                playlists.add(getPlaylistFromCursorImpl(cursor));
            } while (cursor.moveToNext());
        }
        if (cursor != null)
            cursor.close();

        e.onNext(playlists);
        e.onComplete();
    });
}
 
Example 4
Project: ObjectBoxRxJava   File: RxQuery.java   View Source Code Vote up 6 votes
/**
 * The returned Observable emits Query results as Lists.
 * Never completes, so you will get updates when underlying data changes.
 */
public static <T> Observable<List<T>> observable(final Query<T> query) {
    return Observable.create(new ObservableOnSubscribe<List<T>>() {
        @Override
        public void subscribe(final ObservableEmitter<List<T>> emitter) throws Exception {
            final DataSubscription dataSubscription = query.subscribe().observer(new DataObserver<List<T>>() {
                @Override
                public void onData(List<T> data) {
                    if (!emitter.isDisposed()) {
                        emitter.onNext(data);
                    }
                }
            });
            emitter.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    dataSubscription.cancel();
                }
            });
        }
    });
}
 
Example 5
Project: Learning-RxJava   File: Ch2_3.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    Observable<String> source = Observable.create(emitter -> {
        try {
            emitter.onNext("Alpha");
            emitter.onNext("Beta");
            emitter.onNext("Gamma");
            emitter.onNext("Delta");
            emitter.onNext("Epsilon");
            emitter.onComplete();
        } catch (Throwable e) {
            emitter.onError(e);
        }
    });
    Observable<Integer> lengths = source.map(String::length);
    Observable<Integer> filtered = lengths.filter(i -> i >= 5);
    filtered.subscribe(s -> System.out.println("RECEIVED: " +
            s));
}
 
Example 6
Project: Things-Audio-Renderer   File: RxBroadcastReceiver.java   View Source Code Vote up 6 votes
public static Observable<Intent> fromBroadcast(final Context context, final IntentFilter filter) {
    return Observable.create(e -> {


        final BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context1, Intent intent) {
                e.onNext(intent);
            }

        };
        context.registerReceiver(receiver, filter);
        e.setDisposable(new Disposable() {
            @Override
            public void dispose() {
                context.unregisterReceiver(receiver);
            }

            @Override
            public boolean isDisposed() {
                return false;
            }
        });
    });
}
 
Example 7
Project: Subs   File: FirebaseSessionDataStore.java   View Source Code Vote up 6 votes
@Override public Observable<RxDto<UserProfile>> getProfile() {
    final DatabaseReference userProfileRef = userRootRef.child(DatabaseNames.USER_PROFILE);
    return Observable.create(emitter -> {
        final ValueEventListener listener =
                userProfileRef.addValueEventListener(new FirebaseValueListener<UserProfile>() {
                    @Override public void onCancelled(DatabaseError databaseError) {
                        emitter.onError(databaseError.toException());
                    }

                    @Override public void onChildChanged(UserProfile userProfile) {
                        emitter.onNext(new RxDto<>(userProfile));
                    }
                });

        emitter.setCancellable(() -> userProfileRef.removeEventListener(listener));
    });
}
 
Example 8
Project: RetroMusicPlayer   File: M3UWriter.java   View Source Code Vote up 6 votes
public static Observable<File> write(Context context, File dir, Playlist playlist) {
    if (!dir.exists()) //noinspection ResultOfMethodCallIgnored
        dir.mkdirs();
    File file = new File(dir, playlist.name.concat("." + EXTENSION));

    //ArrayList<PlaylistSong> songs = PlaylistSongsLoader.getPlaylistSongList(context, playlist.id);
    return Observable.create(e ->
            PlaylistSongsLoader.getPlaylistSongList(context, playlist.id)
                    .subscribe(songs -> {
                        if (songs.size() > 0) {
                            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                            bw.write(HEADER);
                            for (Song song : songs) {
                                bw.newLine();
                                bw.write(ENTRY + song.duration + DURATION_SEPARATOR + song.artistName + " - " + song.title);
                                bw.newLine();
                                bw.write(song.data);
                            }

                            bw.close();
                        }
                        e.onNext(file);
                        e.onComplete();
                    }));
}
 
Example 9
Project: RetroMusicPlayer   File: HomeLoader.java   View Source Code Vote up 6 votes
public static Observable<ArrayList<Song>> suggestSongs(@NonNull Context context) {
    return Observable.create(observer -> {
        SongLoader.getAllSongs(context).subscribe(songs -> {
            ArrayList<Song> list = new ArrayList<>();
            if (songs.isEmpty()) {
                observer.onNext(new ArrayList<Song>());
                observer.onComplete();
                return;
            }
            ShuffleHelper.makeShuffleList(songs, -1);
            if (songs.size() > 10) {
                list.addAll(songs.subList(0, 10));
            }
            observer.onNext(list);
            observer.onComplete();
        });
    });
}
 
Example 10
Project: Aurora   File: AttentionModel.java   View Source Code Vote up 6 votes
@Override
public Observable<List<MyAttentionEntity>> getMyAttentionList(String userid) {
    return Observable.create((ObservableOnSubscribe<List<MyAttentionEntity>>) emitter -> {

        BmobQuery<MyAttentionEntity> query = new BmobQuery<MyAttentionEntity>();
        query.addWhereEqualTo("userId", userid);
        query.order("-createdAt");
        query.findObjects(new FindListener<MyAttentionEntity>() {
            @Override
            public void done(List<MyAttentionEntity> list, BmobException e) {
                if (list!=null)
                    emitter.onNext(list);
            }
        });
    });
}
 
Example 11
Project: RxGps   File: RxGps.java   View Source Code Vote up 6 votes
private Observable<Boolean> checkPlayServicesAvailable() {
    return Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
            final Activity activity = activityReference.get();
            if (activity != null) {
                final GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
                final int status = apiAvailability.isGooglePlayServicesAvailable(activity);

                if (status != ConnectionResult.SUCCESS) {
                    e.onError(new PlayServicesNotAvailableException());
                } else {
                    e.onNext(true);
                    e.onComplete();
                }
            }
        }
    });
}
 
Example 12
Project: YiZhi   File: RxHelper.java   View Source Code Vote up 5 votes
/**
 * 生成Observable
 *
 * @param t
 * @return Flowable
 */
public static <T> Observable<T> createObservable(final T t) {
    return Observable.create(new ObservableOnSubscribe<T>() {
        @Override
        public void subscribe(ObservableEmitter<T> emitter) throws Exception {
            try {
                emitter.onNext(t);
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    });
}
 
Example 13
Project: exchange-rates-mvvm   File: RealmManagerBase.java   View Source Code Vote up 5 votes
protected <T> Observable<T> readFromRealm(Callable<T> callable) {
    return Observable.create(e -> {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        callable.execute(realm, e);
    } finally {
        if (realm != null) {
            realm.commitTransaction();
            realm.close();
        }
    }
    });
}
 
Example 14
Project: PlayAndroid   File: FeatureRepository.java   View Source Code Vote up 5 votes
@Override
    public Observable<List<Feature>> getData() {
        return Observable.create(new ObservableOnSubscribe<List<Feature>>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<List<Feature>> e) throws Exception {
                List<Feature> features = new ArrayList<>();
                String[] featuresNames = ResUtil.getStringArray(R.array.feature_name);
                Feature feature;
                TypedArray ar = ResUtil.getResources().obtainTypedArray(R.array.feature_logo);
                for (int i = 0; i < ar.length(); i++){
                    int stringResId = ResUtil.getStringId(featuresNames[i]);
//                    String featureName = ResUtil.getString(stringResId);
                    feature = new Feature(i, stringResId, ar.getResourceId(i, 0));
                    features.add(feature);
                }
                ar.recycle();

                /*for (int i = 0; i < featuresNames.length; i++) {
                    int stringResId = ResUtil.getStringId(featuresNames[i]);
                    String featureName = ResUtil.getString(stringResId);
                    String resName = ResUtil.getResName(stringResId);
                    int drawableResId = ResUtil.getDrawableId(resName);
                    feature = new Feature(i, featureName, drawableResId);
                    features.add(feature);
                }*/
                e.onNext(features);
                e.onComplete();
            }
        });
    }
 
Example 15
Project: rx-examples-android   File: MainActivity.java   View Source Code Vote up 5 votes
private Observable<List<Integer>> getObservable() {
  return Observable.create(new ObservableOnSubscribe<List<Integer>>() {
    @Override
    public void subscribe(@NonNull ObservableEmitter<List<Integer>> e) throws Exception {
      e.onNext(Arrays.asList(1, 2, 3, 4, 5));
    }
  });
}
 
Example 16
Project: RxJava4AndroidDemos   File: Create.java   View Source Code Vote up 5 votes
@Override
public void test4() {
    Log.i(TAG, "test4() Create simple demo, onNext() and onComplete() twice");
    Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
            for (int i = 0; i < 3; i++) {
                e.onNext(String.valueOf(i));
            }
            e.onComplete();
        }
    });
    for (int time = 0; time < 2; time++) {
        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d(TAG, "Consumer<String> accept() s: " + s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.d(TAG, "Consumer<Throwable> accept() throwable: " + throwable);
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                Log.d(TAG, "Action run() for onComplete()");
            }
        });
    }
}
 
Example 17
Project: Ghost-Android   File: Observables.java   View Source Code Vote up 5 votes
public static <T> Observable<T> getDialog(ObservableDialogMaker<T> dialogMaker) {
    return Observable.create(emitter -> {
        // confirm save for scheduled and published posts
        final AlertDialog alertDialog = dialogMaker.makeDialog(emitter);

        // dismiss the dialog automatically if this subscriber unsubscribes
        emitter.setCancellable(alertDialog::dismiss);
        alertDialog.show();
    });
}
 
Example 18
Project: jobson   File: JobsDAOTest.java   View Source Code Vote up 5 votes
@Test
public void testPersistStderrSubscribesToTheObservable() {
    final JobDAO dao = getInstance();
    final JobId jobId = dao.persist(STANDARD_VALID_REQUEST).getId();
    final AtomicBoolean daoSubscribedToStderr = new AtomicBoolean(false);
    final Observable<byte[]> stderr = Observable.create(subscriber -> daoSubscribedToStderr.set(true));

    dao.appendStderr(jobId, stderr);

    assertThat(daoSubscribedToStderr.get());
}
 
Example 19
Project: RxFirestore   File: RxFirestoreDb.java   View Source Code Vote up 4 votes
@NonNull
@CheckResult
public static Observable<QuerySnapshot> querySnapshots(@NonNull Query query) {
    return Observable.create(new QuerySnapshotsOnSubscribe(query));
}
 
Example 20
Project: buckaroo   File: Process.java   View Source Code Vote up 4 votes
public Observable<S> states() {

        final Object lock = new Object();

        return Observable.create(new ObservableOnSubscribe<S>() {

            private boolean isComplete = false;

            @Override
            public void subscribe(@NonNull final ObservableEmitter<S> emitter) throws Exception {
                observable.subscribe(
                    next -> {
                        if (isComplete) {
                            if (emitter.isDisposed()) {
                                return;
                            }
                            synchronized (lock) {
                                if (!emitter.isDisposed()) {
                                    emitter.onError(new ProcessException("Process must push exactly one result. "));
                                }
                            }
                        } else {
                            if (next.isRight()) {
                                isComplete = true;
                            } else {
                                emitter.onNext(next.left().get());
                            }
                        }
                    },
                    error -> {
                        if (emitter.isDisposed()) {
                            return;
                        }
                        synchronized (lock) {
                            if (!emitter.isDisposed()) {
                                emitter.onError(error);
                            }
                        }
                    },
                    () -> {
                        if (emitter.isDisposed()) {
                            return;
                        }
                        emitter.onComplete();
                    });
            }
        });
    }