public static Completable userlessAuthentication( final RedditClient reddit, final Credentials credentials) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { try { OAuthData oAuthData = reddit.getOAuthHelper().easyAuth(credentials); reddit.authenticate(oAuthData); e.onComplete(); } catch (Exception ex) { e.onError(ex); } } }); }
public static Completable userAuthentication( final RedditClient reddit, final Credentials credentials, final String url) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { OAuthHelper oAuthHelper = reddit.getOAuthHelper(); try { OAuthData oAuthData = oAuthHelper.onUserChallenge(url, credentials); reddit.authenticate(oAuthData); AuthenticationManager.get().onAuthenticated(oAuthData); e.onComplete(); } catch (Exception ex) { e.onError(ex); } } }); }
public static Completable logout(final Credentials credentials) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { try { AuthenticationManager.get().getRedditClient().getOAuthHelper() .revokeAccessToken(credentials); AuthenticationManager.get().getRedditClient().getOAuthHelper() .revokeRefreshToken(credentials); // Calling deauthenticate() isn't really necessary, since revokeAccessToken() // already calls it. // AuthenticationManager.get().getRedditClient().deauthenticate(); // As of JRAW 9.0.0, revoking the access/refresh token does not update the // auth state to NONE (it instead remains as NEEDS_REFRESH), so to completely // restart the session to a blank state you should re-instantiate the // AuthenticationManager. See https://github.com/mattbdean/JRAW/issues/196 // AuthenticationManager.get().init(...., ....); uncomment this line. e.onComplete(); } catch (Exception ex) { e.onError(ex); } } }); }
@Override public Completable deleteProfile(final String uid) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); rootRef.child(USER_PROFILES) .child(uid) .setValue(null) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
@Override public Completable updateProfile(final Profile profile) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); rootRef.child(USER_PROFILES) .child(profile.getUid()) .setValue(profile) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
@Override public Completable createAccount(final Credentials cred) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } auth.createUserWithEmailAndPassword(cred.getEmail(), cred.getPassword()) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
@Override public Completable attemptLogin(final Credentials cred) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } auth.signInWithEmailAndPassword(cred.getEmail(), cred.getPassword()) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
@Override public Completable deleteUser() { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } final FirebaseUser user = auth.getCurrentUser(); user.delete().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
/** * Set the given value on the specified {@link DatabaseReference}. * * @param ref reference represents a particular location in your database. * @param value value to update. * @return a {@link Completable} which is complete when the set value call finish successfully. */ @NonNull public static Completable setValue(@NonNull final DatabaseReference ref, final Object value) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(@io.reactivex.annotations.NonNull final CompletableEmitter e) throws Exception { ref.setValue(value).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { e.onComplete(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { e.onError(exception); } }); } }); }
/** * Update the specific child keys to the specified values. * * @param ref reference represents a particular location in your database. * @param updateData The paths to update and their new values * @return a {@link Completable} which is complete when the update children call finish successfully. */ @NonNull public static Completable updateChildren(@NonNull final DatabaseReference ref, @NonNull final Map<String, Object> updateData) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter emitter) throws Exception { ref.updateChildren(updateData, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError error, DatabaseReference databaseReference) { if (error != null) { emitter.onError(new RxFirebaseDataException(error)); } else { emitter.onComplete(); } } }); } }); }
/** * Given an operation that takes a {@link MaybeConsumer<Success>}, create a JavaRX * {@link Completable} that succeeds iff the operation does. * * Example: * <pre> * // update the experiment, and then log that it was successful * DataController dc = getDataController(); * MaybeConsumers.buildCompleteable(mc -> dc.updateExperiment(e.getExperimentId(), mc)) * .subscribe(() -> log("successfully updated!")); * </pre> */ public static Completable buildCompleteable( io.reactivex.functions.Consumer<MaybeConsumer<Success>> c) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { c.accept(new MaybeConsumer<Success>() { @Override public void success(Success value) { emitter.onComplete(); } @Override public void fail(Exception e) { emitter.onError(e); } }); } }); }
@Test public void verifyCancellation() { final AtomicInteger i = new AtomicInteger(); //noinspection unchecked because Java Completable source = Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) { e.setCancellable(new Cancellable() { @Override public void cancel() { i.incrementAndGet(); } }); } }); MaybeSubject<Integer> lifecycle = MaybeSubject.create(); source.as(autoDisposable(lifecycle)) .subscribe(); assertThat(i.get()).isEqualTo(0); assertThat(lifecycle.hasObservers()).isTrue(); lifecycle.onSuccess(0); // Verify cancellation was called assertThat(i.get()).isEqualTo(1); assertThat(lifecycle.hasObservers()).isFalse(); }
/** * Delete File from internal Storage * * @param context Context, not null * @param filename Filename of the File that will be deleted * @return <code>Completable</code> that completes with <code>onComplete()</code> when the File is deleted. * <code>onError()</code> is emitted if the given Context is null, filename is null or File is not deleted. */ public static Completable deleteInternal(@Nullable final Context context, final String filename) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { if (context == null) { emitter.onError(new IllegalArgumentException("Context must not be null")); return; } if (filename == null) { emitter.onError(new IllegalArgumentException("Filename must not be null")); return; } File directory = context.getFilesDir(); File file = new File(directory, filename); boolean deleted = file.delete(); if (deleted) { emitter.onComplete(); } else { emitter.onError(new FileNotFoundException()); } } }); }
/** * Converts an {@link ApolloPrefetch} to a synchronous Completable * * @param prefetch the ApolloPrefetch to convert * @return the converted Completable * @throws NullPointerException if prefetch == null */ @Nonnull public static Completable from(@Nonnull final ApolloPrefetch prefetch) { checkNotNull(prefetch, "prefetch == null"); return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter emitter) { cancelOnCompletableDisposed(emitter, prefetch); prefetch.enqueue(new ApolloPrefetch.Callback() { @Override public void onSuccess() { if (!emitter.isDisposed()) { emitter.onComplete(); } } @Override public void onFailure(@Nonnull ApolloException e) { Exceptions.throwIfFatal(e); if (!emitter.isDisposed()) { emitter.onError(e); } } }); } }); }
/** * Set the given value on the specified {@link DatabaseReference}. * * @param ref reference represents a particular location in your database. * @param value value to update. * @return a {@link Completable} which is complete when the set value call finish successfully. */ @NonNull public static Completable setValue(@NonNull final DatabaseReference ref, final Object value) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(@NonNull final CompletableEmitter e) throws Exception { ref.setValue(value).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { e.onComplete(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { e.onError(exception); } }); } }); }
@Override @NonNull public Completable observeClear() { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter emitter) throws Exception { runInWriteLock(readWriteLock, new ThrowingRunnable() { @Override public void run() throws Exception { if (file.exists() && !file.delete()) { throw new IOException("Clear operation on store failed."); } else { emitter.onComplete(); } updateSubject.onNext(ValueUpdate.<T>empty()); } }); } }); }
public static Completable refreshToken(final Credentials credentials) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { try { AuthenticationManager.get().refreshAccessToken(credentials); e.onComplete(); } catch (Exception ex) { e.onError(ex); } } }); }
@Override public Completable createProfile(final Profile profile) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); final DatabaseReference idRef = rootRef.child(USER_PROFILES).child(profile.getUid()); idRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if (!snapshot.exists()) { idRef.setValue(profile).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } else { e.onComplete(); } } @Override public void onCancelled(DatabaseError databaseError) { Log.d("FIREBASE", databaseError.toString()); } }); } } ); }
@Override public Completable logUserOut() { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } listener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { auth.removeAuthStateListener(listener); if (firebaseAuth.getCurrentUser() == null) { e.onComplete(); } else { e.onError(new Exception()); } } }; auth.addAuthStateListener(listener); auth.signOut(); } }); }
@Override public Completable reauthenticateUser(final String password) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { if (auth == null) { auth = FirebaseAuth.getInstance(); } final FirebaseUser user = auth.getCurrentUser(); AuthCredential credential = EmailAuthProvider .getCredential(user.getEmail(), password); user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { e.onComplete(); } else { e.onError(task.getException()); } } }); } }); }
/** * Updates the email address of the user. * * @param firebaseUser current firebaseUser instance. * @param email new email. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable updateEmail(@NonNull final FirebaseUser firebaseUser, @NonNull final String email) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.updateEmail(email)); } }); }
/** * Updates the password of the user. * * @param firebaseUser current firebaseUser instance. * @param password new password. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable updatePassword(@NonNull final FirebaseUser firebaseUser, @NonNull final String password) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.updatePassword(password)); } }); }
/** * Updates the user profile information. * * @param firebaseUser current firebaseUser instance. * @param request {@link UserProfileChangeRequest} request for this user. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable updateProfile(@NonNull final FirebaseUser firebaseUser, @NonNull final UserProfileChangeRequest request) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.updateProfile(request)); } }); }
/** * Deletes the user record from your Firebase project's database. * * @param firebaseUser current firebaseUser instance. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable delete(@NonNull final FirebaseUser firebaseUser) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.delete()); } }); }
/** * Reauthenticates the user with the given credential. * * @param firebaseUser current firebaseUser instance. * @param credential {@link AuthCredential} to re-authenticate. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable reAuthenticate(@NonNull final FirebaseUser firebaseUser, @NonNull final AuthCredential credential) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.reauthenticate(credential)); } }); }
/** * Manually refreshes the data of the current user (for example, attached providers, display name, and so on). * * @param firebaseUser current firebaseUser instance. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable reload(@NonNull final FirebaseUser firebaseUser) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.reload()); } }); }
/** * Initiates email verification for the user. * * @param firebaseUser current firebaseUser instance. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable sendEmailVerification(@NonNull final FirebaseUser firebaseUser) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.sendEmailVerification()); } }); }
/** * Changes the user's password to newPassword for the account for which the code is valid. * Code validity can be checked with {@link FirebaseAuth#verifyPasswordResetCode(String)}. * This use case is only valid for signed-out users, and behavior is undefined for signed-in users. * Password changes for signed-in users should be made using {@link com.google.firebase.auth.FirebaseUser#updatePassword(String)}. * * @param firebaseAuth firebaseAuth instance. * @param code generated code by firebase. * @param newPassword new password for the user. * @return a {@link Completable} which emits when the action is completed. */ @NonNull public static Completable confirmPasswordReset(@NonNull final FirebaseAuth firebaseAuth, @NonNull final String code, @NonNull final String newPassword) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseAuth.confirmPasswordReset(code, newPassword)); } }); }
/** * Applies the given code, which can be any out of band code which is valid according * to {@link FirebaseAuth#checkActionCode(String)} that does not also pass {@link FirebaseAuth#{verifyPasswordResetCode(String)}, * which requires an additional parameter. * * @param firebaseAuth firebaseAuth instance. * @param code generated code by firebase. * @return a {@link Completable} which emits when the action is completed. */ @NonNull public static Completable applyActionCode(@NonNull final FirebaseAuth firebaseAuth, @NonNull final String code) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseAuth.applyActionCode(code)); } }); }
/** * Deletes the object at this {@link StorageReference}. * * @param storageRef represents a reference to a Google Cloud Storage object. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable delete(@NonNull final StorageReference storageRef) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, storageRef.delete()); } }); }
@SuppressWarnings("MissingPermission") @RequiresApi(Build.VERSION_CODES.N) private void startListeningGnssMeasurementsEventsChanges(final GnssMeasurementsEvent.Callback callback) { // This is needed because location manager location updates need a looper Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { checkRegistrationSuccess(locationManager.registerGnssMeasurementsCallback(callback)); } }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(); }
@SuppressWarnings("MissingPermission") @RequiresApi(Build.VERSION_CODES.N) private void startListeningGnssStatusChanges(final GnssStatus.Callback callback) { // This is needed because location manager location updates need a looper Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { checkRegistrationSuccess(locationManager.registerGnssStatusCallback(callback)); } }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(); }
@SuppressWarnings("MissingPermission") private void startListeningLocationChanges(final LocationListener locationListener) { // This is needed because location manager location updates need a looper Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, sensorConfig.getMinSensorDelay(getSensorType()), MIN_DISTANCE, locationListener); } }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(); }
@RequiresApi(Build.VERSION_CODES.N) private void startListeningGnssNavigationMessages(final GnssNavigationMessage.Callback callback) { // This is needed because location manager location updates need a looper Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { checkRegistrationSuccess(locationManager.registerGnssNavigationMessageCallback(callback)); } }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(); }
/** * @param task * @param <R> Usually <Void> * @return */ @CheckReturnValue @NonNull public static <R> Completable completes(@NonNull final Task<R> task) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(@NonNull final CompletableEmitter emit) throws Exception { task.addOnCompleteListener(RxTask.<R>listener(emit)); } }); }
@Override public Completable deleteAlarm(final Alarm alarm) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); RealmQuery<RealmAlarm> query = realm.where(RealmAlarm.class); query.equalTo("alarmId", alarm.getAlarmId()); RealmResults<RealmAlarm> result = query.findAll(); if (result.size() == 0) { realm.cancelTransaction(); e.onError(new Exception()); } else { result.deleteFromRealm(0); realm.commitTransaction(); e.onComplete(); } } } ); }
@Override public Completable updateAlarm(final Alarm alarm) { return Completable.create( new CompletableOnSubscribe() { @Override public void subscribe(final CompletableEmitter e) throws Exception { Realm realm = Realm.getDefaultInstance(); realm.beginTransaction(); RealmAlarm realmAlarm = new RealmAlarm(); realmAlarm.setAlarmId(alarm.getAlarmId()); realmAlarm.setHourOfDay(alarm.getHourOfDay()); realmAlarm.setMinute(alarm.getMinute()); realmAlarm.setAlarmTitle(alarm.getAlarmTitle()); realmAlarm.setActive(alarm.isActive()); realmAlarm.setVibrateOnly(alarm.isVibrateOnly()); realmAlarm.setRenewAutomatically(alarm.isRenewAutomatically()); realm.copyToRealmOrUpdate(realmAlarm); realm.commitTransaction(); e.onComplete(); } } ); }
protected void waitForFinishedCampaignProcess(@Nullable final Runnable callback){ Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(@NonNull CompletableEmitter completableEmitter) throws Exception { while (!isCampaignProcessFinished()){ InstrumentationRegistry.getInstrumentation().waitForIdleSync(); } if (callback != null) { callback.run(); } completableEmitter.onComplete(); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .blockingAwait(130, TimeUnit.SECONDS); }
/** * Write Content to a File in internal Storage * * @param context Context, not null * @param filename Filename of the File that will be saved * @param content Content to write into the File * @return <code>Observable<Void></code> that completes with <code>onComplete()</code> when the File is saved. * <code>onError()</code> is emitted if the given Context is null or File operation meets an <code>IOException</code> */ @NonNull public static Completable writeInternal(@Nullable final Context context, final String filename, final String content) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { if (context == null) { emitter.onError(new IllegalArgumentException("Context must not be null")); return; } if (filename == null) { emitter.onError(new IllegalArgumentException("Filename must not be null")); return; } if (content == null) { emitter.onError(new IllegalArgumentException("Content must not be null")); return; } FileOutputStream outputStream = null; try { outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(content.getBytes()); outputStream.close(); emitter.onComplete(); } catch (IOException e) { emitter.onError(e); } } }); }