io.reactivex.functions.Function Java Examples
The following examples show how to use
io.reactivex.functions.Function.
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: MovieListFragment.java From AFBaseLibrary with Apache License 2.0 | 6 votes |
@Override public void loadData(int page) { Observable.just(page).map(new Function<Integer, List<MovieEntity>>() { @Override public List<MovieEntity> apply(Integer integer) throws Exception { String movies = getJson(getAFContext(), "douban_movie.json"); return new Gson().fromJson(movies, new TypeToken<List<MovieEntity>>() { }.getType()); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new ApiCallback<List<MovieEntity>>(this) { @Override public void onNext(List<MovieEntity> movieEntities) { mItems.clear(); mItems.addAll(movieEntities); refreshLoadComplete(isSuccess(movieEntities), false); } @Override public void onError(Throwable e) { refreshLoadComplete(false, false); } }); }
Example #2
Source File: RxBleConnectionMock.java From RxAndroidBle with Apache License 2.0 | 6 votes |
@Override public Completable writeDescriptor(@NonNull final UUID serviceUuid, @NonNull final UUID characteristicUuid, @NonNull final UUID descriptorUuid, @NonNull final byte[] data) { return discoverServices() .flatMap(new Function<RxBleDeviceServices, SingleSource<BluetoothGattDescriptor>>() { @Override public SingleSource<BluetoothGattDescriptor> apply(RxBleDeviceServices rxBleDeviceServices) { return rxBleDeviceServices.getDescriptor(serviceUuid, characteristicUuid, descriptorUuid); } }) .doOnSuccess(new Consumer<BluetoothGattDescriptor>() { @Override public void accept(BluetoothGattDescriptor bluetoothGattDescriptor) throws Exception { bluetoothGattDescriptor.setValue(data); } }) .toCompletable(); }
Example #3
Source File: RxPayUtils.java From RxPay with Apache License 2.0 | 6 votes |
public static ObservableTransformer<WxPayResult, WxPayResult> checkWechatResult() { return new ObservableTransformer<WxPayResult, WxPayResult>() { @Override public ObservableSource<WxPayResult> apply(Observable<WxPayResult> payResultObservable) { return payResultObservable.map(new Function<WxPayResult, WxPayResult>() { @Override public WxPayResult apply(WxPayResult wxPayResult) { if (!wxPayResult.isSucceed()) { throw new PayFailedException(String.valueOf(wxPayResult.getErrCode()), wxPayResult.getErrInfo()); } return wxPayResult; } }); } }; }
Example #4
Source File: HistoryTableConnection.java From mimi-reader with Apache License 2.0 | 6 votes |
public static Flowable<History> watchThread(final String boardName, final long threadId) { From query = new Select() .from(History.class) .where(History.KEY_NAME + "=?", boardName) .where(History.KEY_THREAD_ID + "=?", threadId); Log.d(LOG_TAG, "SQL=" + query.toSql()); BriteDatabase db = MimiApplication.getInstance().getBriteDatabase(); return db.createQuery(History.TABLE_NAME, query.toSql(), (Object[]) query.getArguments()) .toFlowable(BackpressureStrategy.BUFFER) .map(runQuery()) .flatMap(History.flowableMapper()) .flatMap((Function<List<History>, Flowable<History>>) histories -> { if (histories == null || histories.size() == 0) { return Flowable.just(new History()); } return Flowable.just(histories.get(0)); }) .onErrorResumeNext((Function<Throwable, Flowable<History>>) throwable -> { Log.e(LOG_TAG, "Error fetching history", throwable); return Flowable.just(new History()); }); }
Example #5
Source File: NullAwayRxSupportNegativeCases.java From NullAway with MIT License | 6 votes |
private Observable<Integer> filterThenMapNullableContainerMergesReturns( Observable<NullableContainer<String>> observable) { return observable .filter( new Predicate<NullableContainer<String>>() { @Override public boolean test(NullableContainer<String> container) throws Exception { if (perhaps() && container.get() != null) { return true; } else { return (container.get() != null); } } }) .map( new Function<NullableContainer<String>, Integer>() { @Override public Integer apply(NullableContainer<String> c) throws Exception { return c.get().length(); } }); }
Example #6
Source File: ISHNewsDetailModel.java From AcgClub with MIT License | 6 votes |
@Override public Flowable<SHPostDetail> getAcgNewsDetail(int postId) { return mRepositoryManager.obtainRetrofitService(AcgNewsService.class) .getISHNewsDetail(postId) .flatMap(new Function<SHResponse<SHPostDetail>, Flowable<SHPostDetail>>() { @Override public Flowable<SHPostDetail> apply(SHResponse<SHPostDetail> response) { if (!TextUtils.isEmpty(response.getErrMsg())) { return Flowable.error(new ApiException(response.getErrMsg())); } else if (response.getData() != null) { return RxUtil.createData(response.getData()); } else { return Flowable.error(new ApiException("数据加载失败")); } } }); }
Example #7
Source File: TripRepository.java From InstantAppSample with Apache License 2.0 | 6 votes |
public Maybe<Trip> getTrip(final String tripId) { return getTrips() .toObservable() .flatMap(new Function<List<Trip>, ObservableSource<? extends Trip>>() { @Override public ObservableSource<? extends Trip> apply(List<Trip> tripList) throws Exception { return Observable.fromIterable(tripList); } }) .filter(new Predicate<Trip>() { @Override public boolean test(Trip trip) throws Exception { return trip.getId().equals(tripId); } }) .singleElement(); }
Example #8
Source File: TransformersTest.java From mobius with Apache License 2.0 | 6 votes |
@Test public void processingLongEffectsDoesNotBlockProcessingShorterEffects() { final List<String> effects = Arrays.asList("Hello", "Rx"); PublishSubject<String> upstream = PublishSubject.create(); Function<String, Integer> sleepyFunction = s -> { try { Thread.sleep(duration(s)); } catch (InterruptedException ie) { } return s.length(); }; final List<Integer> results = new ArrayList<>(); upstream .compose(Transformers.fromFunction(sleepyFunction, Schedulers.io())) .subscribe(results::add); Observable.fromIterable(effects).subscribe(upstream); await().atMost(durationForEffects(effects)).until(() -> results.equals(expected(effects))); }
Example #9
Source File: RxUtils.java From WanAndroid with Apache License 2.0 | 6 votes |
/** * 对结果进行预处理 */ public static <T> ObservableTransformer<BaseResponse<T>, T> handleResult(){ return new ObservableTransformer<BaseResponse<T>, T>() { @Override public ObservableSource<T> apply(Observable<BaseResponse<T>> upstream) { return upstream.flatMap(new Function<BaseResponse<T>, ObservableSource<T>>() { @Override public ObservableSource<T> apply(BaseResponse<T> tBaseResponse) throws Exception { if(tBaseResponse.getErrorCode() == 0){ return createObservable(tBaseResponse.getData());//创建我们需要的数据 } return Observable.error( new ApiException(tBaseResponse.getErrorCode(), tBaseResponse.getErrorMsg())//创建一个异常 ); } }); } }; }
Example #10
Source File: Strings.java From rxjava2-extras with Apache License 2.0 | 5 votes |
public static Flowable<String> strings(Flowable<?> source) { return source.map(new Function<Object, String>() { @Override public String apply(Object t) throws Exception { return String.valueOf(t); } }); }
Example #11
Source File: Processor.java From state-machine with Apache License 2.0 | 5 votes |
private Processor(Function<Class<?>, EntityBehaviour<?, Id>> behaviourFactory, Scheduler processingScheduler, Scheduler signalScheduler, Flowable<Signal<?, Id>> signals, Function<GroupedFlowable<ClassId<?, Id>, EntityStateMachine<?, Id>>, Flowable<EntityStateMachine<?, Id>>> entityTransform, FlowableTransformer<Signal<?, Id>, Signal<?, Id>> preGroupBy, Function<Consumer<Object>, Map<ClassId<?, Id>, Object>> mapFactory, Action3<? super EntityStateMachine<?, Id>, ? super Event<?>, ? super EntityState<?>> preTransitionAction, Consumer<? super EntityStateMachine<?, Id>> postTransitionAction) { Preconditions.checkNotNull(behaviourFactory); Preconditions.checkNotNull(signalScheduler); Preconditions.checkNotNull(signals); Preconditions.checkNotNull(entityTransform); Preconditions.checkNotNull(preGroupBy); Preconditions.checkNotNull(preTransitionAction); Preconditions.checkNotNull(postTransitionAction); // mapFactory is nullable this.behaviourFactory = behaviourFactory; this.signalScheduler = signalScheduler; this.processingScheduler = processingScheduler; this.subject = PublishSubject.create(); this.signals = signals; this.entityTransform = entityTransform; this.preGroupBy = preGroupBy; this.mapFactory = mapFactory; this.signallerClock = Clock.from(signalScheduler); this.preTransitionAction = preTransitionAction; this.postTransitionAction = postTransitionAction; }
Example #12
Source File: ManyToManyActivity.java From storio with Apache License 2.0 | 5 votes |
@NonNull Disposable subscribeToPersonsAndCars() { Set<String> tables = new HashSet<String>(3); tables.add(PersonTable.NAME); tables.add(CarTable.NAME); tables.add(PersonCarRelationTable.TABLE); return Flowable.merge( storIOSQLite.observeChangesInTables(tables, LATEST), Flowable.just(Changes.newInstance(PersonCarRelationTable.TABLE)) ) .map(new Function<Changes, List<Person>>() { @Override public List<Person> apply(Changes changes) { return storIOSQLite.get() .listOfObjects(Person.class) .withQuery(Query.builder().table(PersonTable.NAME).build()) .prepare() .executeAsBlocking(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Person>>() { @Override public void accept(List<Person> persons) { if(persons.isEmpty()) { addPersons(); } else { personsAdapter.setPersons(persons); } } }); }
Example #13
Source File: RxValue.java From rxfirebase with Apache License 2.0 | 5 votes |
/** * @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 #14
Source File: RetryWhenNetworkException.java From NewFastFrame with Apache License 2.0 | 5 votes |
@Override public Observable<?> apply(@NonNull Observable<? extends Throwable> observable) throws Exception { return observable .zipWith(Observable.range(1, count + 1), (BiFunction<Throwable, Integer, Wrapper>) Wrapper::new).flatMap((Function<Wrapper, ObservableSource<?>>) wrapper -> { if ((wrapper.throwable instanceof ConnectException || wrapper.throwable instanceof SocketTimeoutException || wrapper.throwable instanceof TimeoutException) && wrapper.index < count + 1) { //如果超出重试次数也抛出错误,否则默认是会进入onCompleted return Observable.timer(delay + (wrapper.index - 1) * increaseDelay, TimeUnit.MILLISECONDS); } return Observable.error(wrapper.throwable); }); }
Example #15
Source File: AddEditTaskEffectHandlers.java From mobius-android-sample with Apache License 2.0 | 5 votes |
static Function<CreateTask, AddEditTaskEvent> createTaskHandler( TasksDataSource remoteSource, TasksDataSource localSource) { return createTaskEffect -> { Task task = Task.create(UUID.randomUUID().toString(), createTaskEffect.taskDetails()); try { remoteSource.saveTask(task); localSource.saveTask(task); return taskCreatedSuccessfully(); } catch (Exception e) { return taskCreationFailed("Failed to create task"); } }; }
Example #16
Source File: PollActivity.java From RxEasyHttp with Apache License 2.0 | 5 votes |
public void onPollRequestCount(View view) { //http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world int count = 3;//轮询3次 //方式一:采用intervalRange //Observable.intervalRange(0,count,0,5, TimeUnit.SECONDS).flatMap(new Function<Long, ObservableSource<Content>>() { //方式一:采用take countdisposable = Observable.interval(0, 5, TimeUnit.SECONDS).take(count).flatMap(new Function<Long, ObservableSource<Content>>() { @Override public ObservableSource<Content> apply(@NonNull Long aLong) throws Exception { return EasyHttp.get("/ajax.php") .baseUrl("http://fy.iciba.com") .params("a", "fy") .params("f", "auto") .params("t", "auto") .params("w", "hello world") //采用代理 .execute(new CallClazzProxy<TestApiResult6<Content>, Content>(Content.class) { }); } }).subscribeWith(new BaseSubscriber<Content>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onNext(@NonNull Content content) { showToast(content.toString()); } }); }
Example #17
Source File: ProcessThreadTask.java From mimi-reader with Apache License 2.0 | 5 votes |
public static Function<ChanThread, ChanThread> processThread(final List<Long> userPosts, final String boardName, final long threadId) { return thread -> { if (thread == null) { return ChanThread.empty(); } return processThread(thread.getPosts(), userPosts, boardName, threadId); }; }
Example #18
Source File: RxUtils.java From Awesome-WanAndroid with Apache License 2.0 | 5 votes |
/** * 退出登录返回结果处理 * @param <T> 指定的泛型类型 * @return ObservableTransformer */ public static <T> ObservableTransformer<BaseResponse<T>, T> handleLogoutResult() { return httpResponseObservable -> httpResponseObservable.flatMap((Function<BaseResponse<T>, Observable<T>>) baseResponse -> { if(baseResponse.getErrorCode() == BaseResponse.SUCCESS && CommonUtils.isNetworkConnected()) { //创建一个非空数据源,避免onNext()传入null return createData(CommonUtils.cast(new LoginData())); } else { return Observable.error(new OtherException()); } }); }
Example #19
Source File: AutoViewHolder.java From AutoAdapter with Apache License 2.0 | 5 votes |
public Observable<AutoViewHolder> getViewHolderOnChildLongClickObservable(@IdRes int viewId) { return RxView.longClicks(itemView.findViewById(viewId)) .map(new Function<Object, AutoViewHolder>() { @Override public AutoViewHolder apply(Object o) { return AutoViewHolder.this; } }); }
Example #20
Source File: Call.java From rxjava2-jdbc with Apache License 2.0 | 5 votes |
static <T1, T2> Flowable<Notification<CallableResultSet2<T1, T2>>> createWithTwoResultSets( Single<Connection> connection, String sql, Flowable<List<Object>> parameterGroups, List<ParameterPlaceholder> parameterPlaceholders, Function<? super ResultSet, ? extends T1> f1, Function<? super ResultSet, ? extends T2> f2, int fetchSize) { return connection.toFlowable().flatMap( con -> createWithTwoResultSets(con, sql, parameterGroups, parameterPlaceholders, f1, f2, fetchSize)); }
Example #21
Source File: SplashModel.java From Aurora with Apache License 2.0 | 5 votes |
@Override public Observable<List<Category>> getCategories() { Observable<List<Category>> categories = mRepositoryManager.obtainRetrofitService(SplashService.class) .getCategories(); return mRepositoryManager.obtainCacheService(CommonCache.class) .getCategories(categories) .flatMap(new Function<Reply<List<Category>>, ObservableSource<List<Category>>>() { @Override public ObservableSource<List<Category>> apply(@NonNull Reply<List<Category>> listReply) throws Exception { return Observable.just(listReply.getData()); } }); }
Example #22
Source File: Filter.java From mimi-reader with Apache License 2.0 | 5 votes |
public static Function<Cursor, Observable<List<Filter>>> mapper() { return cursor -> { cursor.moveToPosition(-1); List<Filter> filters = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { Filter filter = new Filter(); filter.loadFromCursor(cursor); filters.add(filter); } return Observable.just(filters); }; }
Example #23
Source File: SignUpPresenter.java From playa with MIT License | 5 votes |
@Override public void signUp(String username, String password, String repassword) { Observable<BaseResponse<LoginResponse>> observable = dataManager.signup(username, password, repassword); observable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .map(new Function<BaseResponse<LoginResponse>, LoginResponse>() { @Override public LoginResponse apply(@NonNull BaseResponse<LoginResponse> response) throws Exception { return response.getData(); } }) .subscribeWith(new Observer<LoginResponse>() { @Override public void onSubscribe(@NonNull Disposable d) { disposable = d; } @Override public void onNext(@NonNull LoginResponse loginResponse) { } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); }
Example #24
Source File: RxBleClientImpl.java From RxAndroidBle with Apache License 2.0 | 5 votes |
private Observable<RxBleScanResult> createScanOperationApi18(@Nullable final UUID[] filterServiceUUIDs) { final Set<UUID> filteredUUIDs = uuidUtil.toDistinctSet(filterServiceUUIDs); final LegacyScanOperation scanOperation = new LegacyScanOperation(filterServiceUUIDs, rxBleAdapterWrapper, uuidUtil); return operationQueue.queue(scanOperation) .doFinally(new Action() { @Override public void run() { synchronized (queuedScanOperations) { queuedScanOperations.remove(filteredUUIDs); } } }) .mergeWith(this.<RxBleInternalScanResultLegacy>bluetoothAdapterOffExceptionObservable()) .map(new Function<RxBleInternalScanResultLegacy, RxBleScanResult>() { @Override public RxBleScanResult apply(RxBleInternalScanResultLegacy scanResult) { return convertToPublicScanResult(scanResult); } }) .doOnNext(new Consumer<RxBleScanResult>() { @Override public void accept(RxBleScanResult rxBleScanResult) { RxBleLog.i("%s", rxBleScanResult); } }) .share(); }
Example #25
Source File: GrpcRetry.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Retries a streaming gRPC call immediately. * * @param operation the gRPC operation to retry, typically from a generated reactive-grpc stub class * @param <I> I * @param <O> O */ public static <I, O> SingleConverter<I, Flowable<O>> retryImmediately(final Function<Single<I>, Flowable<O>> operation) { return retryWhen(operation, new Function<Flowable<Throwable>, Publisher<?>>() { @Override public Publisher<?> apply(Flowable<Throwable> errors) { return errors; } }); }
Example #26
Source File: ThreadHelper.java From AndroidGodEye with Apache License 2.0 | 5 votes |
public static void setupRxjava() { TestScheduler testScheduler = new TestScheduler(); RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler scheduler) throws Exception { return testScheduler; } }); }
Example #27
Source File: AllocineApi.java From Android-Allocine-Api with Apache License 2.0 | 5 votes |
public Single<List<Theater>> theaterList(final String lat, final String lng, final int radius, 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.LAT, lat, AllocineService.LONG, lng, AllocineService.RADIUS, "" + radius, 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<Theater>>>() { @Override public SingleSource<? extends List<Theater>> apply(Pair<String, String> pair) throws Exception { return allocineService.theaterlist(lat, lng, radius, count, page, pair.first, pair.second) .map(new Function<AllocineResponse, List<Theater>>() { @Override public List<Theater> apply(AllocineResponse allocineResponse) throws Exception { return allocineResponse.getFeed().getTheater(); } }); } }) .compose(this.<List<Theater>>retry()); }
Example #28
Source File: ComplexStorage.java From web3j with Apache License 2.0 | 5 votes |
public RemoteFunctionCall<TransactionReceipt> setBaz(Baz _toSet) { final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( FUNC_SETBAZ, Arrays.<Type>asList(_toSet), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function); }
Example #29
Source File: ProjectPresenter.java From playa with MIT License | 5 votes |
@Override public void getProjectCategories() { Observable<BaseResponse<List<Category>>> observable = dataManager.getProjectCategories(); observable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .map(new Function<BaseResponse<List<Category>>, List<Category>>() { @Override public List<Category> apply(@NonNull BaseResponse<List<Category>> response) throws Exception { return response.getData(); } }).subscribeWith(new Observer<List<Category>>() { @Override public void onSubscribe(@NonNull Disposable d) { disposable = d; } @Override public void onNext(@NonNull List<Category> categories) { getView().createTabs(categories); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); }
Example #30
Source File: AllocineApi.java From Android-Allocine-Api with Apache License 2.0 | 5 votes |
/** * Recherche */ public Single<AllocineResponse> search(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<? extends AllocineResponse>>() { @Override public SingleSource<? extends AllocineResponse> apply(Pair<String, String> pair) throws Exception { return allocineService.search(recherche, ServiceSecurity.applatir(filter), count, page, pair.first, pair.second); } }) .compose(this.<AllocineResponse>retry()); }