io.reactivex.SingleEmitter Java Examples

The following examples show how to use io.reactivex.SingleEmitter. 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: RealListStore.java    From RxStore with Apache License 2.0 6 votes vote down vote up
@Override @NonNull public Single<List<T>> observeClear() {
  return Single.create(new SingleOnSubscribe<List<T>>() {
    @Override public void subscribe(final SingleEmitter<List<T>> 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.");
          }

          emitter.onSuccess(Collections.<T>emptyList());
          updateSubject.onNext(Collections.<T>emptyList());
        }
      });
    }
  });
}
 
Example #2
Source File: RxValue.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param emit
 * @return
 */
@NonNull
@CheckReturnValue
public static ValueEventListener listener(@NonNull final SingleEmitter<DataSnapshot> emit) {
    return new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!emit.isDisposed()) {
                emit.onSuccess(dataSnapshot);
            }
        }

        @Override
        public void onCancelled(DatabaseError e) {
            if (!emit.isDisposed()) {
                emit.onError(e.toException());
            }
        }
    };
}
 
Example #3
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param emit
 * @return
 */
@NonNull
@CheckReturnValue
public static ValueEventListener listener(@NonNull final SingleEmitter<DataSnapshot> emit) {
    return new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (!emit.isDisposed()) {
                emit.onSuccess(dataSnapshot);
            }
        }

        @Override
        public void onCancelled(DatabaseError e) {
            if (!emit.isDisposed()) {
                emit.onError(e.toException());
            }
        }
    };
}
 
Example #4
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> single(@NonNull final Query query) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = listener(emit);

            emit.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    query.removeEventListener(listener);
                }
            });

            query.addListenerForSingleValueEvent(listener);
        }
    });
}
 
Example #5
Source File: RealListStore.java    From RxStore with Apache License 2.0 6 votes vote down vote up
@Override @NonNull public Single<List<T>> observeAdd(@NonNull final T value) {
  assertNotNull(value, "value");

  return Single.create(new SingleOnSubscribe<List<T>>() {
    @Override public void subscribe(final SingleEmitter<List<T>> emitter) throws Exception {
      runInWriteLock(readWriteLock, new ThrowingRunnable() {
        @Override public void run() throws Exception {
          if (!file.exists() && !file.createNewFile()) {
            throw new IOException("Could not create file for store.");
          }

          List<T> originalList = converter.read(file, type);
          if (originalList == null) originalList = Collections.emptyList();

          List<T> result = new ArrayList<T>(originalList.size() + 1);
          result.addAll(originalList);
          result.add(value);

          converterWrite(result, converter, type, file);
          emitter.onSuccess(result);
          updateSubject.onNext(result);
        }
      });
    }
  });
}
 
Example #6
Source File: RxQuery.java    From ObjectBoxRxJava with Apache License 2.0 6 votes vote down vote up
/**
 * The returned Single emits one Query result as a List.
 */
public static <T> Single<List<T>> single(final Query<T> query) {
    return Single.create(new SingleOnSubscribe<List<T>>() {
        @Override
        public void subscribe(final SingleEmitter<List<T>> emitter) throws Exception {
            query.subscribe().single().observer(new DataObserver<List<T>>() {
                @Override
                public void onData(List<T> data) {
                    if (!emitter.isDisposed()) {
                        emitter.onSuccess(data);
                    }
                }
            });
            // no need to cancel, single never subscribes
        }
    });
}
 
Example #7
Source File: RxProcess.java    From RxShell with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
public Single<Boolean> isAlive() {
    if (RXSDebug.isDebug()) Timber.tag(TAG).v("isAlive()");
    return Single
            .create((SingleEmitter<Boolean> emitter) -> {
                if (ApiWrap.hasOreo()) {
                    emitter.onSuccess(process.isAlive());
                } else {
                    try {
                        process.exitValue();
                        emitter.onSuccess(false);
                    } catch (IllegalThreadStateException e) {
                        emitter.onSuccess(true);
                    }
                }
            })
            .subscribeOn(Schedulers.io());
}
 
Example #8
Source File: RxValue.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @param query
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> single(@NonNull final Query query) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            final ValueEventListener listener = listener(emit);

            emit.setCancellable(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    query.removeEventListener(listener);
                }
            });

            query.addListenerForSingleValueEvent(listener);
        }
    });
}
 
Example #9
Source File: Rx2Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloStoreOperation} to a Single.
 *
 * @param operation the ApolloStoreOperation to convert
 * @param <T>       the value type
 * @return the converted Single
 */
@NotNull
@CheckReturnValue
public static <T> Single<T> from(@NotNull final ApolloStoreOperation<T> operation) {
  checkNotNull(operation, "operation == null");
  return Single.create(new SingleOnSubscribe<T>() {
    @Override
    public void subscribe(final SingleEmitter<T> emitter) {
      operation.enqueue(new ApolloStoreOperation.Callback<T>() {
        @Override
        public void onSuccess(T result) {
          emitter.onSuccess(result);
        }

        @Override
        public void onFailure(Throwable t) {
          emitter.onError(t);
        }
      });
    }
  });
}
 
Example #10
Source File: BookRepository.java    From NovelReader with MIT License 6 votes vote down vote up
/************************************************************/
public Single<Void> deleteCollBookInRx(CollBookBean bean) {
    return Single.create(new SingleOnSubscribe<Void>() {
        @Override
        public void subscribe(SingleEmitter<Void> e) throws Exception {
            //查看文本中是否存在删除的数据
            deleteBook(bean.get_id());
            //删除任务
            deleteDownloadTask(bean.get_id());
            //删除目录
            deleteBookChapter(bean.get_id());
            //删除CollBook
            mCollBookDao.delete(bean);
            e.onSuccess(new Void());
        }
    });
}
 
Example #11
Source File: CompositeBurstNodeService.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
private <T> Single<T> compositeSingle(Collection<Single<T>> singles) {
    return Single.create((SingleEmitter<T> emitter) -> {
        AtomicInteger errorCount = new AtomicInteger(0);
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        emitter.setCancellable(compositeDisposable::dispose);
        for (Single<T> single : singles) {
            compositeDisposable.add(single.subscribe(emitter::onSuccess, error -> {
                synchronized (errorCount) {
                    if (errorCount.incrementAndGet() == singles.size()) { // Every single has errored
                        emitter.tryOnError(error);
                    }
                }
            }));
        }
    })
            .subscribeOn(BurstKitUtils.defaultBurstNodeServiceScheduler());
}
 
Example #12
Source File: RxLocationSingleOnSubscribe.java    From RxGps with Apache License 2.0 6 votes vote down vote up
@Override
public final void subscribe(SingleEmitter<T> emitter) throws Exception {
    final GoogleApiClient apiClient = createApiClient(new ApiClientConnectionCallbacks(emitter));

    try {
        apiClient.connect();
    } catch (Throwable ex) {
        emitter.onError(ex);
    }

    emitter.setCancellable(() -> {
        if (apiClient.isConnected()) {
            onUnsubscribed(apiClient);
        }

        apiClient.disconnect();
    });
}
 
Example #13
Source File: RxActionDelegate.java    From pandroid with Apache License 2.0 6 votes vote down vote up
public static <T> Single<T> single(final OnSubscribeAction<T> subscribe) {
    return Single.<T>create(new SingleOnSubscribe<T>() {
        @Override
        public void subscribe(final SingleEmitter<T> emitter) throws Exception {
            RxActionDelegate<T> delegate = new RxActionDelegate<>(new ActionDelegate<T>() {
                @Override
                public void onSuccess(T result) {
                    emitter.onSuccess(result);
                }

                @Override
                public void onError(Exception e) {
                    emitter.onError(e);
                }
            });
            emitter.setDisposable(delegate);
            subscribe.subscribe(delegate);
        }
    });
}
 
Example #14
Source File: RealListStore.java    From RxStore with Apache License 2.0 6 votes vote down vote up
@Override @NonNull public Single<List<T>> observeRemove(final int position) {
  return Single.create(new SingleOnSubscribe<List<T>>() {
    @Override public void subscribe(final SingleEmitter<List<T>> emitter) throws Exception {
      runInWriteLock(readWriteLock, new ThrowingRunnable() {
        @Override public void run() throws Exception {
          List<T> originalList = converter.read(file, type);
          if (originalList == null) originalList = Collections.emptyList();

          List<T> modifiedList = new ArrayList<T>(originalList);
          modifiedList.remove(position);

          converterWrite(modifiedList, converter, type, file);
          emitter.onSuccess(modifiedList);
          updateSubject.onNext(modifiedList);
        }
      });
    }
  });
}
 
Example #15
Source File: SettingsCheckHandleSingleOnSubscribe.java    From RxGps with Apache License 2.0 6 votes vote down vote up
static void onResolutionResult(String observableId, int resultCode) {
    if (observableMap.containsKey(observableId)) {
        SettingsCheckHandleSingleOnSubscribe observable = observableMap.get(observableId).get();

        if (observable != null && observable.emitterWeakRef != null) {
            SingleEmitter<Boolean> observer = observable.emitterWeakRef.get();

            if (observer != null) {
                observer.onSuccess(resultCode == Activity.RESULT_OK);
            }
        }

        observableMap.remove(observableId);
    }

    observableMapCleanup();
}
 
Example #16
Source File: DataService.java    From android-mvvm with Apache License 2.0 6 votes vote down vote up
public Single<Result<String>> loadData() {
    return Single.create(new SingleOnSubscribe<Result<String>>() {
        @Override
        public void subscribe(SingleEmitter<Result<String>> e) throws Exception {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            if (new Random().nextBoolean()) {
                e.onSuccess(Result.success("Result from data service"));
            } else {
                e.onSuccess(Result.<String>error(new Throwable("Fake error")));
            }
        }
    }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread());
}
 
Example #17
Source File: AbstractQuery.java    From Android-OkGraphQl with Apache License 2.0 6 votes vote down vote up
public Single<T> toSingle() {
    return Single.create(new SingleOnSubscribe<T>() {
        @Override
        public void subscribe(final @NonNull SingleEmitter<T> e) throws Exception {
            enqueue(new Callback<T>() {
                        @Override
                        public void onResponse(@NonNull T data) {
                            e.onSuccess(data);
                        }
                    }
                    , new ErrorCallback() {
                        @Override
                        public void onError(@NonNull Throwable error) {
                            e.onError(error);
                        }
                    }
            );
        }
    });
}
 
Example #18
Source File: RealListStore.java    From RxStore with Apache License 2.0 6 votes vote down vote up
@Override @NonNull public Single<List<T>> get() {
  return Single.create(new SingleOnSubscribe<List<T>>() {
    @Override public void subscribe(final SingleEmitter<List<T>> emitter) throws Exception {
      runInReadLock(readWriteLock, new ThrowingRunnable() {
        @Override public void run() throws Exception {
          if (!file.exists()) {
            emitter.onSuccess(Collections.<T>emptyList());
            return;
          }

          List<T> list = converter.read(file, type);
          if (list == null) list = Collections.emptyList();
          emitter.onSuccess(list);
        }
      });
    }
  });
}
 
Example #19
Source File: RxRealmUtils.java    From AcgClub with MIT License 5 votes vote down vote up
public static <T> Single<T> singleExec(final RealmConfiguration configuration,
    final Consumer<Pair<SingleEmitter, Realm>> emitter) {
  return Single.create(new SingleOnSubscribe<T>() {
    @Override
    public void subscribe(SingleEmitter<T> e) throws Exception {
      try (Realm realm = Realm.getInstance(configuration)) {
        emitter.accept(new Pair<SingleEmitter, Realm>(e, realm));
      }
    }
  });
}
 
Example #20
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
/**
 * Recherche
 */
public Single<AllocineResponseSmall> searchSmall(final String recherche, final List<String> filter, final int count, final int page) {
    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.Q, "" + recherche.replace(" ", "+"),
                            AllocineService.FILTER, filter,
                            AllocineService.COUNT, "" + count,
                            AllocineService.PAGE, "" + page
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<AllocineResponseSmall>>() {
                @Override
                public SingleSource<AllocineResponseSmall> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.searchSmall(recherche, ServiceSecurity.applatir(filter), count, page, pair.first, pair.second);
                }
            })
            .compose(this.<AllocineResponseSmall>retry());
}
 
Example #21
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
/**
 * Informations sur un film
 */
public Single<Movie> movie(final String idFilm, final Profile profile) {
    final String filter = FILTER_MOVIE;

    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {

                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.CODE, idFilm,
                            AllocineService.PROFILE, profile.getValue(),
                            AllocineService.FILTER, filter
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<? extends Movie>>() {
                @Override
                public SingleSource<? extends Movie> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.movie(idFilm, profile.getValue(), filter, pair.first, pair.second)
                            .map(new Function<AllocineResponse, Movie>() {
                                @Override
                                public Movie apply(AllocineResponse allocineResponse) throws Exception {
                                    return allocineResponse.getMovie();
                                }
                            });
                }
            })
            .compose(this.<Movie>retry());
}
 
Example #22
Source File: DisposableUtil.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
public static <T> DisposableSingleObserver<T> disposableSingleObserverFromEmitter(final SingleEmitter<T> emitter) {
    return new DisposableSingleObserver<T>() {

        @Override
        public void onSuccess(T t) {
            emitter.onSuccess(t);
        }

        @Override
        public void onError(Throwable e) {
            emitter.tryOnError(e);
        }
    };
}
 
Example #23
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
/**
 * Informations sur une personne
 */
public Single<PersonFull> person(final String idPerson, final String profile, final String filter) {
    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.CODE, idPerson,
                            AllocineService.PROFILE, profile,
                            AllocineService.FILTER, filter
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<PersonFull>>() {
                @Override
                public SingleSource<PersonFull> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.person(idPerson, profile, filter, pair.first, pair.second)
                            .map(new Function<AllocineResponse, PersonFull>() {
                                @Override
                                public PersonFull apply(AllocineResponse allocineResponse) throws Exception {
                                    return allocineResponse.getPerson();
                                }
                            });
                }
            })
            .compose(this.<PersonFull>retry());
}
 
Example #24
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
/**
 * Filmographie d'une personne
 */
public Single<List<Participation>> filmography(final String idPerson, final String profile, final String filter) {
    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.CODE, idPerson,
                            AllocineService.PROFILE, profile,
                            AllocineService.FILTER, filter
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<List<Participation>>>() {
                @Override
                public SingleSource<List<Participation>> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.filmography(idPerson, profile, filter, pair.first, pair.second)
                            .map(new Function<AllocineResponse, List<Participation>>() {
                                @Override
                                public List<Participation> apply(AllocineResponse allocineResponse) throws Exception {
                                    return allocineResponse.getPerson().getParticipation();
                                }
                            });
                }
            })
            .compose(this.<List<Participation>>retry());
}
 
Example #25
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
public Single<List<Movie>> movieList(List<MovieListFilter> filter, final Profile profile, final MovieListOrder order, final int count, final int page) {
    final List<String> filterString = new ArrayList<>();
    for (MovieListFilter movieListFilter : filter) {
        filterString.add(movieListFilter.getValue());
    }

    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(true,
                            AllocineService.FILTER, filterString,
                            AllocineService.PROFILE, profile.getValue(),
                            AllocineService.ORDER, order.getValue(),
                            AllocineService.COUNT, "" + count,
                            AllocineService.PAGE, "" + page
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<? extends List<Movie>>>() {
                @Override
                public SingleSource<? extends List<Movie>> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.movieList(ServiceSecurity.applatir(filterString), profile.getValue(), order.getValue(), count, page, pair.first, pair.second)
                            .map(new Function<AllocineResponse, List<Movie>>() {
                                @Override
                                public List<Movie> apply(AllocineResponse allocineResponse) throws Exception {
                                    return allocineResponse.getFeed().getMovie();
                                }
                            });
                }
            })
            .compose(this.<List<Movie>>retry());
}
 
Example #26
Source File: AllocineApi.java    From Android-Allocine-Api with Apache License 2.0 5 votes vote down vote up
public Single<List<PersonFull>> starsList(final List<PersonListFilter> filter, final Profile profile, final int count, final int page) {
    final List<String> filterString = new ArrayList<>();
    for (PersonListFilter movieListFilter : filter) {
        filterString.add(movieListFilter.getValue());
    }

    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(true,
                            AllocineService.FILTER, filterString,
                            AllocineService.PROFILE, profile.getValue(),
                            AllocineService.COUNT, "" + count,
                            AllocineService.PAGE, "" + page
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<? extends List<PersonFull>>>() {
                @Override
                public SingleSource<? extends List<PersonFull>> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.personList(ServiceSecurity.applatir(filterString), profile.getValue(), count, page, pair.first, pair.second)
                            .map(new Function<AllocineResponse, List<PersonFull>>() {
                                @Override
                                public List<PersonFull> apply(AllocineResponse allocineResponse) throws Exception {
                                    return allocineResponse.getFeed().getPerson();
                                }
                            });
                }
            })
            .compose(this.<List<PersonFull>>retry());
}
 
Example #27
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}
 
Example #28
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @param fireLocalEvents
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function), fireLocalEvents);
        }
    });
}
 
Example #29
Source File: SingleOnSubscribeExecuteAsBlockingOptional.java    From storio with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(@NonNull SingleEmitter<Optional<Result>> emitter) throws Exception {
    try {
        final Result value = preparedOperation.executeAsBlocking();
        emitter.onSuccess(Optional.of(value));
    } catch (Exception e) {
        emitter.onError(e);
    }
}
 
Example #30
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}