Java Code Examples for io.reactivex.functions.Consumer

The following are top voted examples for showing how to use io.reactivex.functions.Consumer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: MaybeThrowingTest.java   Source Code and License 7 votes vote down vote up
@Test public void resultThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingMaybeObserver<Result<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.result().subscribe(new ForwardingObserver<Result<String>>(observer) {
    @Override public void onSuccess(Result<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 2
Project: buffer-slayer   File: SenderConsumerBridge.java   Source Code and License 6 votes vote down vote up
/**
 * Adapt a {@link Sender} to rx-java's {@link Consumer}
 */
@SuppressWarnings("unchecked")
static <M extends Message, R> Consumer<List<SendingTask<M>>> toConsumer(final Sender<M, R> sender) {
  return new Consumer<List<SendingTask<M>>>() {
    @Override
    public void accept(List<SendingTask<M>> tasks) throws Exception {
      if (tasks.isEmpty()) return;
      logger.debug("Sending {} messages.", tasks.size());

      Object[] messageAndDeferred = SendingTask.unzipGeneric(tasks);
      final List<M> messages = (List<M>) messageAndDeferred[0];
      final List<Deferred> deferreds = (List<Deferred>) messageAndDeferred[1];

      try {
        List<R> result = sender.send(messages);
        Deferreds.resolveAll(result, deferreds);
      } catch (Throwable t) {
        Deferreds.rejectAll(MessageDroppedException.dropped(t, messages), deferreds, messages);
      }
    }
  };
}
 
Example 3
Project: https-github.com-hyb1996-NoRootScriptDroid   File: MyScriptListFragment.java   Source Code and License 6 votes vote down vote up
private void doDeletingScriptFile() {
    mScriptListWithProgressBarView.showProgressBar();
    Observable.fromPublisher(new Publisher<Boolean>() {
        @Override
        public void subscribe(Subscriber<? super Boolean> s) {
            s.onNext(PFile.deleteRecursively(mSelectedScriptFile));
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(@io.reactivex.annotations.NonNull Boolean deleted) throws Exception {
                    showMessage(deleted ? R.string.text_already_delete : R.string.text_delete_failed);
                    notifyScriptFileChanged();
                    onScriptFileOperated();
                }
            });
}
 
Example 4
Project: RxBeacon   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RxBeacon.with(this)
            //.addBeaconParser(RxBeaconParser.ESTIMOTE)
            .beaconsInRegion()
            .subscribe(new Consumer<RxBeaconRange>() {
                @Override
                public void accept(@NonNull RxBeaconRange rxBeaconRange) throws Exception {
                    Log.d("beaconsInRegion", rxBeaconRange.toString());
                }
            });

    //RxBeacon.with(this)
    //        .addBeaconParser("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")
    //        .monitor()
    //        .subscribe(new Consumer<RxBeaconMonitor>() {
    //            @Override
    //            public void accept(@NonNull RxBeaconMonitor rxBeaconMonitor) throws Exception {
    //                Log.d("monitor", rxBeaconMonitor.toString());
    //            }
    //        });
}
 
Example 5
Project: GitHub   File: MainPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void onCardExhausted() {
    getCompositeDisposable().add(getDataManager()
            .getAllQuestions()
            .subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Consumer<List<Question>>() {
                @Override
                public void accept(List<Question> questionList) throws Exception {
                    if (!isViewAttached()) {
                        return;
                    }

                    if (questionList != null) {
                        getMvpView().reloadQuestionnaire(questionList);
                    }
                }
            }));
}
 
Example 6
Project: Rxjava2.0Demo   File: MapActivity.java   Source Code and License 6 votes vote down vote up
private void map() {
    Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(ObservableEmitter<Integer> e) throws Exception {
            e.onNext(1);
            e.onNext(2);
            e.onNext(3);
        }
    }).map(new Function<Integer, String>() {
        @Override
        public String apply(Integer integer) throws Exception {
            return "This is result " + integer;
        }
    }).subscribe(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            Log.e(MainActivity.TAG, "accept: " + Thread.currentThread().getName());
            info += s + "\n";
            tv.setText(info);
        }
    });
}
 
Example 7
Project: TheNounProject   File: HomePresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void loadSearchHistory() {
    getCompositeDisposableHelper().addDisposable(getDataManager()
            .getSearchHistory()
            .compose(getCompositeDisposableHelper().<List<OrmHistory>>applySchedulers())
            .subscribe(new Consumer<List<OrmHistory>>() {
                @Override
                public void accept(List<OrmHistory> histories) throws Exception {
                    if (!histories.isEmpty()) {
                        getMvpView().showSearchHistory(histories);
                    } else {
                        getMvpView().showEmptySearchHistory();
                    }
                }
            }));
}
 
Example 8
Project: NeteaseCloudMusic   File: ConfigPresenter.java   Source Code and License 6 votes vote down vote up
public void requestLoadingList() {
    Observable.create(new ObservableOnSubscribe<List<ConfigBean>>() {
        @Override
        public void subscribe(ObservableEmitter<List<ConfigBean>> e) throws Exception {
            mModel = ConfigModel.getInstance(configView.getContext());
            e.onNext(mModel.getConfigList());
            mModel.setConfigCallback(ConfigPresenter.this);
        }
    })
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<ConfigBean>>() {
                @Override
                public void accept(List<ConfigBean> list) throws Exception {
                    configView.displayConfigList(list);
                }
            });

}
 
Example 9
Project: AliZhiBoHao   File: WebActivity.java   Source Code and License 6 votes vote down vote up
public void checkVersion(){
    ZBHClient.getInstance()
            .create(ZBHServices.class, Constants.BASE_UPGRADE_URL)
            .getVersionInfo()
            .subscribeOn(Schedulers.io())//在子线程做请求处理
            .observeOn(AndroidSchedulers.mainThread())//回到主线程做数据处理
            .subscribe(new Consumer<VersionBean>() {
                @Override
                public void accept(VersionBean versionBean) throws Exception {
                    //弹出提示并更新
                    showUpgradeDialog(versionBean);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {

                }
            });
}
 
Example 10
Project: POCenter   File: SearchPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void loadMore(int start) {
    application.getRepertories()
            .getList(start, COUNT, null, RemoteApi.Status.RECRUITING, keywords, false)
            .subscribe(new Consumer<List<ProjectBean>>() {
                @Override
                public void accept(List<ProjectBean> projectBeen) throws Exception {
                    getView().addData(projectBeen);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    getView().loadMoreError(throwable);
                }
            });
}
 
Example 11
Project: AssistantBySDK   File: RealTimeUpdateSearchBox.java   Source Code and License 6 votes vote down vote up
/**
 * 弹出键盘(可能存在视图尚未加载完成,需要延迟一段时间弹出)
 **/
public void showKeyboard() {
    Single.just(0)
            .delay(300, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSuccess(new Consumer<Integer>() {
                @Override
                public void accept(Integer integer) throws Exception {
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    edit.requestFocus();
                    imm.showSoftInput(edit, 0);
                }
            })
            .subscribeOn(Schedulers.io())
            .subscribe();

}
 
Example 12
Project: AvenueNet   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void put() {
    AvenueNetClient.builder("put")
            .param("name", "putname")
            .build()
            .put()
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
}
 
Example 13
Project: KTools   File: ImageActivity.java   Source Code and License 6 votes vote down vote up
@OnClick(R.id.btn_take_picture)
public void onBtnTakePictureClicked() {
    rxPermissions.request(Manifest.permission.CAMERA)
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        openCamera();
                    } else {
                        ToastUtils.showShortToast("权限被拒绝");
                    }
                }

            });

}
 
Example 14
Project: filepicker   File: Util.java   Source Code and License 6 votes vote down vote up
public static void externalStorage(final RequestPermission requestPermission, final PickerContract.IPickerView view) {
    RxPermissions rxPermissions = new RxPermissions((Activity) view);
    boolean isPermissionsGranted =
            rxPermissions
                    .isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (isPermissionsGranted) {
        requestPermission.onRequestPermissionSuccess();
    } else {
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            requestPermission.onRequestPermissionSuccess();
                        } else {
                            view.showMessage(((Activity) view).getResources().getString(R.string.request_permission_fail));
                        }
                    }
                });
    }
}
 
Example 15
Project: many-faced-view   File: CustomAnimationTestActivity.java   Source Code and License 6 votes vote down vote up
private void delayAndSwitchToState(@ViewState int state) {
    disposable = Flowable.just(state)
            .delay(3000, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Integer>() {
                @Override
                public void accept(Integer currentState) throws Exception {
                    stateView.setState(currentState);
                    if (currentState == ViewState.CONTENT) {
                        displayContents();
                        delayAndSwitchToState(ViewState.LOADING);
                    } else {
                        delayAndSwitchToState(ViewState.CONTENT);
                    }
                }
            });
}
 
Example 16
Project: J-Chain   File: GuardTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void onErrorAcceptWithCrashingFunctionThenThrowException() {

    Guard.call(new Callable<TestClass>() {
        @Override
        public TestClass call() throws Exception {
            throw new NullPointerException();
        }
    }).onError(new Consumer<Exception>() {

        @Override
        public void accept(@NonNull Exception e) throws Exception {
            throw new UnsupportedOperationException();
        }
    });

}
 
Example 17
Project: filepicker   File: Util.java   Source Code and License 6 votes vote down vote up
public static void launchRecorder(final RequestPermission requestPermission, final PickerContract.IPickerView view) {
    RxPermissions rxPermissions = new RxPermissions((Activity) view);
    boolean isPermissionsGranted =
            rxPermissions
                    .isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
                    rxPermissions
                            .isGranted(Manifest.permission.RECORD_AUDIO);
    if (isPermissionsGranted) {
        requestPermission.onRequestPermissionSuccess();
    } else {
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.RECORD_AUDIO)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            requestPermission.onRequestPermissionSuccess();
                        } else {
                            view.showMessage(((Activity) view).getResources().getString(R.string.request_permission_fail));
                        }
                    }
                });
    }
}
 
Example 18
Project: AssistantBySDK   File: TingPlayProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * 合成并显示回复文本
 **/
private void synthesizeAndShowResp(final List<Track> tracks, String content, final int finalPlayIndex) {
    EventBus.getDefault().post(new ChatMsgEvent(new ResponseMsg(content), null, null, null));
    SynthesizerBase.get().startSpeakAbsolute(content)
            .doOnNext(new Consumer<SpeechMsg>() {
                @Override
                public void accept(SpeechMsg speechMsg) throws Exception {
                    if (speechMsg.state() == SpeechMsg.State.OnBegin)
                        EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_START));
                }
            })
            .doOnComplete(new Action() {
                @Override
                public void run() throws Exception {
                    EventBus.getDefault().post(new SynthesizeEvent(SynthesizeEvent.SYNTH_END));
                    if (tracks != null)
                        XmlyManager.get().getPlayer().playList(tracks, finalPlayIndex);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.computation())
            .subscribe();

}
 
Example 19
Project: Aequorea   File: ArticlePresenter.java   Source Code and License 6 votes vote down vote up
public void loadRecommendedArticles(long id) {
    mComposite.add(mService.getRecommendedArticle(id)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<Data>() {
            @Override
            public void accept(Data data) throws Exception {
                
                mBaseView.onRecommendationLoaded(filterData(data.getData()));
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                mBaseView.onRecommendationError(throwable);
            }
        }));
}
 
Example 20
Project: PlayAndroid   File: SplashActivity.java   Source Code and License 6 votes vote down vote up
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

//        checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

//        getWindow().setBackgroundDrawableResource(R.drawable.splash_bg);

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        Log.d(TAG, "permission is all granted: " + aBoolean);
                        doNext();
                    }
                });

    }
 
Example 21
Project: Rxjava2.0Demo   File: CreateActivity.java   Source Code and License 6 votes vote down vote up
private void window() {
    Log.e(TAG, "window: window");
    Observable.interval(1, TimeUnit.SECONDS)
            .take(15)
            .window(3, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Observable<Long>>() {
                @Override
                public void accept(Observable<Long> longObservable) throws Exception {
                    Log.e(TAG, "accept: begin...");
                    longObservable.subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) throws Exception {
                                    Log.e(TAG, "accept: " + aLong);
                                }
                            });
                }
            });
}
 
Example 22
Project: GitHub   File: ObservableThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void bodyThrowingInOnCompleteDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingObserver<String> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.body().subscribe(new ForwardingObserver<String>(observer) {
    @Override public void onComplete() {
      throw e;
    }
  });

  observer.assertAnyValue();
  assertThat(throwableRef.get()).isSameAs(e);

}
 
Example 23
Project: GitHub   File: AsyncTest.java   Source Code and License 6 votes vote down vote up
@Test public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException {
  server.enqueue(new MockResponse());

  final CountDownLatch latch = new CountDownLatch(1);
  final AtomicReference<Throwable> errorRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!errorRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
      }
      latch.countDown();
    }
  });

  TestObserver<Void> observer = new TestObserver<>();
  final RuntimeException e = new RuntimeException();
  service.completable().subscribe(new ForwardingCompletableObserver(observer) {
    @Override public void onComplete() {
      throw e;
    }
  });

  latch.await(1, SECONDS);
  assertThat(errorRef.get()).isSameAs(e);
}
 
Example 24
Project: GitHub   File: SingleThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingSingleObserver<Response<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.response().subscribe(new ForwardingObserver<Response<String>>(observer) {
    @Override public void onSuccess(Response<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 25
Project: RetrofitRxjavaDemo   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public void onJokeClick(View view) {
    Random random = new Random();
    int id = random.nextInt(11);
    HttpHelper.request(mSubscriptions, HttpBuilder.getAPIService().getJokeById1(id))
            .subscribe(new Consumer<JokeResult>() {
                @Override
                public void accept(JokeResult jokeResult) {
                    // 处理返回数据
                    mTvContent.setText(jokeResult.joke);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    // 处理错误数据
                    Log.e(TAG, "accept() called with: throwable = [" + throwable + "]");
                }
            });
}
 
Example 26
Project: rx-redux   File: RxStoreTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGetStates() throws Exception {
    Consumer<Integer> callback = Mockito.mock(Consumer.class);
    Consumer<Integer> callback2 = Mockito.mock(Consumer.class);
    store = new RxStore<>(initialState, this::reducer);

    store.getStates().subscribe(callback);
    verify(callback, never()).accept(any());

    store.dispatch(INC);
    verify(callback).accept(initialState + 1);

    store.getStates().map(i -> i * (-1)).subscribe(callback2); // we can map without changing the other subscriptions
    verify(callback2, never()).accept(any());

    store.dispatch(INC);
    verify(callback).accept(initialState + 2);
    verify(callback2).accept((initialState + 2) * (-1));

    assertEquals("subscribing through states should not change the outcome", initialState + 2, store.getState().intValue());
}
 
Example 27
Project: YiZhi   File: HeadSettingActivity.java   Source Code and License 6 votes vote down vote up
@OnClick({R.id.tv_cancel, R.id.tv_ok})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.tv_cancel:
            onBackPressedSupport();
            break;
        case R.id.tv_ok:
            Observable.create(new ObservableOnSubscribe<Uri>() {
                @Override
                public void subscribe(ObservableEmitter<Uri> e) throws
                        Exception {
                    e.onNext(generateUri());
                    e.onComplete();
                }
            }).compose(RxHelper.<Uri>rxSchedulerHelper())
                    .subscribe(new Consumer<Uri>() {
                        @Override
                        public void accept(Uri uri) throws Exception {
                            RxEventHeadBean rxEventHeadBean = new RxEventHeadBean(uri);
                            RxBus.get().send(RX_BUS_CODE_HEAD_IMAGE_URI, rxEventHeadBean);
                            onBackPressedSupport();
                        }
                    });
            break;
    }
}
 
Example 28
Project: RxJava2-Android-Sample   File: TakeUntilExampleActivity.java   Source Code and License 6 votes vote down vote up
/**
 * takeUntil与skipUntil操作符作用相反,订阅并开始发射原始Observable,它还监视你提供的第二个Observable。
 * 如果第二个Observable发射了一项数据或者发射了一个终止通知( onError通知或一个onComplete通知),
 * TakeUntil返回的Observable会停止发射原始Observable并终止。
 */
private void doSomeWork() {
    if (!isRunning) {
        Observable
                .interval(1, TimeUnit.SECONDS)
                .take(6)
                .takeUntil(Observable.just(10).delay(3, TimeUnit.SECONDS))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        isRunning = true;
                    }
                })
                .doOnTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        isRunning = false;
                    }
                })
                // Run on a background thread
                .subscribeOn(Schedulers.io())
                // Be notified on the main thread
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver());
    }
}
 
Example 29
Project: RxJava4AndroidDemos   File: Map.java   Source Code and License 6 votes vote down vote up
@Override
public void test0() {
    Log.i(TAG, "test0() Map simple demo, integer 1,2,3 transform to string 2,4,6");
    Observable.just(1, 2, 3).map(new Function<Integer, String>() {
        @Override
        public String apply(@NonNull Integer integer) throws Exception {
            return Integer.toString(integer * 2);
        }
    }).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 30
Project: GitHub   File: WelcomePresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void getWelcomeData() {
    addSubscribe(mDataManager.fetchWelcomeInfo(RES)
            .compose(RxUtil.<WelcomeBean>rxSchedulerHelper())
            .subscribe(new Consumer<WelcomeBean>() {
                @Override
                public void accept(WelcomeBean welcomeBean) {
                    mView.showContent(welcomeBean);
                    startCountDown();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mView.jumpToMain();
                }
            })
    );
}
 
Example 31
Project: FCM-for-Mojo   File: AbsWhitelistActivity.java   Source Code and License 6 votes vote down vote up
private void fetchWhitelistState() {
    mCompositeDisposable.add(startFetchWhitelistState()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WhitelistState>() {
                @Override
                public void accept(WhitelistState state) throws Exception {
                    mServerWhitelistState = state;

                    mToggleContainer.setEnabled(true);
                    mToggle.setEnabled(true);
                    mToggle.setChecked(state.isEnabled());
                    mAdapter.updateData(state);
                    mRefreshed = true;

                    invalidateOptionsMenu();

                    onFetchSucceed(state);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Toast.makeText(getApplicationContext(), getString(R.string.toast_something_wroing, throwable.getMessage()), Toast.LENGTH_SHORT).show();
                }
            }));
}
 
Example 32
Project: RxJava2-Android-Sample   File: SkipUntilExampleActivity.java   Source Code and License 6 votes vote down vote up
/**
 * SkipUntil订阅原始的Observable,但是忽略它的发射物,直到第二个Observable发射了一项数据那一刻,它开始发射原始Observable。
 */
private void doSomeWork() {
    if (!isRunning) {
        Observable
                .interval(1, TimeUnit.SECONDS)
                .take(6)
                .skipUntil(Observable.just(10).delay(3, TimeUnit.SECONDS))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        isRunning = true;
                    }
                })
                .doOnTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        isRunning = false;
                    }
                })
                // Run on a background thread
                .subscribeOn(Schedulers.io())
                // Be notified on the main thread
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getObserver());
    }
}
 
Example 33
Project: GitHub   File: RxJavaTests.java   Source Code and License 6 votes vote down vote up
@Test
@RunTestInLooperThread
public void realmResults_emittedOnUpdate() {
    final AtomicInteger subscriberCalled = new AtomicInteger(0);
    Realm realm = looperThread.getRealm();
    realm.beginTransaction();
    RealmResults<AllTypes> results = realm.where(AllTypes.class).findAll();
    realm.commitTransaction();

    subscription = results.asFlowable().subscribe(new Consumer<RealmResults<AllTypes>>() {
        @Override
        public void accept(RealmResults<AllTypes> allTypes) throws Exception {
            if (subscriberCalled.incrementAndGet() == 2) {
                looperThread.testComplete();
            }
        }
    });

    realm.beginTransaction();
    realm.createObject(AllTypes.class);
    realm.commitTransaction();
}
 
Example 34
Project: GitHub   File: RxJavaTests.java   Source Code and License 6 votes vote down vote up
@Test
@UiThreadTest
public void dynamicRealmObject_emitChangesetOnSubscribe() {
    DynamicRealm dynamicRealm = DynamicRealm.getInstance(realm.getConfiguration());
    dynamicRealm.beginTransaction();
    final DynamicRealmObject obj = dynamicRealm.createObject(AllTypes.CLASS_NAME);
    dynamicRealm.commitTransaction();

    final AtomicBoolean subscribedNotified = new AtomicBoolean(false);
    subscription = obj.asChangesetObservable().subscribe(new Consumer<ObjectChange<RealmObject>>() {
        @Override
        public void accept(ObjectChange<RealmObject> change) throws Exception {
            assertTrue(change.getObject() == obj);
            assertNull(change.getChangeset());
            subscribedNotified.set(true);
        }
    });
    assertTrue(subscribedNotified.get());
    subscription.dispose();
    dynamicRealm.close();
}
 
Example 35
Project: YiZhi   File: ZhihuPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void loadLatestList() {
    if (mIModel == null)
        return;

    mRxManager.register(mIModel.getDailyList().subscribe(new Consumer<ZhihuDailyListBean>() {
        @Override
        public void accept(ZhihuDailyListBean zhihuDailyListBean) throws Exception {
            mDate = zhihuDailyListBean.getDate();
            //Logger.e("mDate = " + mDate);

            if (mIView != null)
                mIView.updateContentList(zhihuDailyListBean.getStories());
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            if (mIView != null) {
                if (mIView.isVisiable())
                    mIView.showToast("Network error.");
                mIView.showNetworkError();
            }
        }
    }));
}
 
Example 36
Project: android-mvp-architecture   File: MainPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void onCardExhausted() {
    getCompositeDisposable().add(getDataManager()
            .getAllQuestions()
            .subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Consumer<List<Question>>() {
                @Override
                public void accept(List<Question> questionList) throws Exception {
                    if (!isViewAttached()) {
                        return;
                    }

                    if (questionList != null) {
                        getMvpView().reloadQuestionnaire(questionList);
                    }
                }
            }));
}
 
Example 37
Project: RefreshWithAppBarLayout   File: WithBottomTabActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 延时2s添加数据
 */
private void addData(final boolean refresh) {
    Observable
            .timer(2, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(new Consumer<Long>() {
                @Override
                public void accept(@NonNull Long aLong) throws Exception {
                    if (refresh) {
                        mDatas.add(0, "Added after refresh...");
                        dataAdapter.setDatasAndNotify(mDatas);
                        contentView.setLastUpdatedLabel(formatDateTime(System.currentTimeMillis()));
                        contentView.onPullDownRefreshComplete();
                    }
                }
            })
            .subscribe();
}
 
Example 38
Project: GitHub   File: RxJavaTests.java   Source Code and License 6 votes vote down vote up
@Test
@UiThreadTest
public void realmList_emittedOnSubscribe() {
    final AtomicBoolean subscribedNotified = new AtomicBoolean(false);
    realm.beginTransaction();
    final RealmList<Dog> list = realm.createObject(AllTypes.class).getColumnRealmList();
    realm.commitTransaction();
    subscription = list.asFlowable().subscribe(new Consumer<RealmList<Dog>>() {
        @Override
        @SuppressWarnings("ReferenceEquality")
        public void accept(RealmList<Dog> rxList) throws Exception {
            assertTrue(rxList == list);
            subscribedNotified.set(true);
        }
    });
    assertTrue(subscribedNotified.get());
    subscription.dispose();
}
 
Example 39
Project: https-github.com-hyb1996-NoRootScriptDroid   File: ViewSampleActivity.java   Source Code and License 5 votes vote down vote up
@OnClick(R.id.edit)
void edit() {
    new ScriptOperations(this, mView)
            .importSample(mSample)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(@NonNull String path) throws Exception {
                    EditActivity.editFile(ViewSampleActivity.this, path);
                    finish();
                }
            });
}
 
Example 40
Project: AssistantBySDK   File: NaviSetLinePresenter.java   Source Code and License 5 votes vote down vote up
/**
 * 由于服务端2分钟无交互则清空上下文对象,每2分钟上传一次导航引擎,保证导航状态正常
 **/
private void keepNavigation() {
    cancelDisposable();
    mDisposable = Observable.interval(2, 2, TimeUnit.MINUTES)
            .observeOn(Schedulers.io())
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    uploadNavigation();
                    if (mNavigation == null) {
                        throw new RuntimeException("导航结束了。。。");
                    }
                }
            });
}
 
Example 41
Project: https-github.com-hyb1996-NoRootScriptDroid   File: ScriptOperations.java   Source Code and License 5 votes vote down vote up
public void newDirectory() {
    showNameInputDialog("", new InputCallback())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(@io.reactivex.annotations.NonNull String path) throws Exception {
                    if (new ScriptFile(getCurrentDirectory(), path).mkdirs()) {
                        showMessage(R.string.text_already_create);
                        notifyScriptFileChanged();
                    } else {
                        showMessage(R.string.text_create_fail);
                    }
                }
            });
}
 
Example 42
Project: showroom-android   File: RxFaker.java   Source Code and License 5 votes vote down vote up
private static void subscriberListener(@NonNull final WeakReference<FakerReadyListener> refListener) {
    final Disposable disposable = getInstance().subscribe(new Consumer<Faker>() {
        @Override
        public void accept(Faker faker) throws Exception {
            final FakerReadyListener listener = refListener.get();
            if (listener != null) {
                listener.onFakerReady(faker);
            }
        }
    });
}
 
Example 43
Project: Android-Gank-Share   File: CollectFragment.java   Source Code and License 5 votes vote down vote up
private void loadData(){
    Observable
            .create(new ObservableOnSubscribe<List<CollectItem>>() {
                @Override
                public void subscribe(ObservableEmitter<List<CollectItem>> e) throws Exception {
                    mItemList.clear();
                    e.onNext(DataSupport.findAll(CollectItem.class));
                }
            })
            .map(new Function<List<CollectItem>, Boolean>() {
                @Override
                public Boolean apply(List<CollectItem> items) throws Exception {
                    return items != null && items.size() > 0
                            && mItemList.addAll(items);
                }
            })
            .subscribeOn(Schedulers.io())
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    addDisposable(disposable);
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    showEmptyView(!aBoolean);
                    mAdapter.notifyDataSetChanged();
                }
            });
}
 
Example 44
Project: GitHub   File: MainPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void onDrawerOptionLogoutClick() {
    getMvpView().showLoading();

    getCompositeDisposable().add(getDataManager().doLogoutApiCall()
            .subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Consumer<LogoutResponse>() {
                @Override
                public void accept(LogoutResponse response) throws Exception {
                    if (!isViewAttached()) {
                        return;
                    }

                    getDataManager().setUserAsLoggedOut();
                    getMvpView().hideLoading();
                    getMvpView().openLoginActivity();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    if (!isViewAttached()) {
                        return;
                    }

                    getMvpView().hideLoading();

                    // handle the login error here
                    if (throwable instanceof ANError) {
                        ANError anError = (ANError) throwable;
                        handleApiError(anError);
                    }
                }
            }));

}
 
Example 45
Project: Melophile   File: SingleInteractor.java   Source Code and License 5 votes vote down vote up
public void execute(Consumer<? super T> onSuccess, Consumer<? super Throwable> onError, Params params){
    Single<T> single= buildUseCase(params);
    if(single!=null) {
            single=single.subscribeOn(schedulerProvider.io())
                         .observeOn(schedulerProvider.ui());
        disposables.add(single.subscribe(onSuccess, onError));
    }
}
 
Example 46
Project: RxDiffUtil   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mCounterTextView = (TextView) findViewById(R.id.counterTextView);
    mRestartButton = (Button) findViewById(R.id.restart_button);

    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.sample_recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    mUpdatedSampleModelList = new ArrayList<>();

    mSampleAdapter = new SampleAdapter();
    recyclerView.setAdapter(mSampleAdapter);

    // The request manager can be injected using Dagger
    mDiffRequestManager = RxDiffUtil
            .bindTo(this)
            .with(mSampleAdapter);

    mCompositeDisposable.add(mDiffRequestManager
            .diffResults()
            .subscribe(new Consumer<RxDiffResult>() {
                @Override
                public void accept(@NonNull RxDiffResult rxDiffResult) throws Exception {
                    Log.d(TAG, "Diff calculations completed successfully!");
                    setUpdateCompleteState();
                }
            }));

    restartAdapterUpdating();
}
 
Example 47
Project: Mount   File: MountReceiver.java   Source Code and License 5 votes vote down vote up
private void onBootCompleted(final Context context) {
    PolicyUtils.umountAll(context, new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            IntentUtils.startCocaService(context);
        }
    });
}
 
Example 48
Project: rx-examples-android   File: BufferActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_buffer);
  ButterKnife.bind(this);
  setTitle(TAG);
  setup();

  Observable.fromIterable(list)
      .subscribeOn(Schedulers.io())
      .observeOn(Schedulers.computation())
      //buffers the results and emits after a given timespan
      //Do read docs(cmd+click on mac)
      .buffer(2, TimeUnit.MICROSECONDS, 5)
      .map(new Function<List<String>, Integer>() {
        @Override
        public Integer apply(@NonNull List<String> strings) throws Exception {
          //size of current emission
          int size = strings.size();
          Log.i(TAG, "Last emission size: " + size);
          total += size;
          return size;
        }
      })
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Consumer<Integer>() {
        @Override
        public void accept(Integer count) throws Exception {
          textviewBuffer.setText("TOTAL EMITTED: " + total);
        }
      });
}
 
Example 49
Project: Mix   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void initDemoRX02() {
        Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Log.e(TAG, "Observable thread is : " + Thread.currentThread().getName());
                Log.e(TAG, "emit 1");
                emitter.onNext(1);
            }
        });

        Consumer<Integer> consumer = new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                Log.e(TAG, "Observer thread is :" + Thread.currentThread().getName());
                Log.e(TAG, "onNext: " + integer);
            }
        };

//        observable.subscribe(consumer);

        /*
        * 多次指定上游的线程只有第一次指定的有效, 也就是说多次调用subscribeOn() 只有第一次的有效.
          多次指定下游的线程是可以的, 也就是说每调用一次observeOn() , 下游的线程就会切换一次.
        * */
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);
    }
 
Example 50
Project: Metronome-Android   File: AboutActivity.java   Source Code and License 5 votes vote down vote up
private void subscribe() {
    if (themesView != null && appIcon != null) {
        themesView.subscribe();
        appIcon.subscribe();
    }

    textColorPrimarySubscription = Aesthetic.get()
            .textColorPrimary()
            .subscribe(new Consumer<Integer>() {
                @Override
                public void accept(@NonNull Integer integer) throws Exception {
                    if (toolbar != null && iconView != null && buttonsView != null && librariesView != null) {
                        toolbar.setTitleTextColor(integer);
                        DrawableCompat.setTint(toolbar.getBackground(), integer);
                        DrawableCompat.setTint(iconView.getBackground(), integer);
                        DrawableCompat.setTint(buttonsView.getBackground(), integer);
                        DrawableCompat.setTint(creditsView.getBackground(), integer);
                        DrawableCompat.setTint(librariesView.getBackground(), integer);
                    }

                    ActionBar actionBar = getSupportActionBar();
                    if (actionBar != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        Drawable drawable = ContextCompat.getDrawable(AboutActivity.this, R.drawable.ic_back);
                        DrawableCompat.setTint(drawable, integer);
                        actionBar.setHomeAsUpIndicator(drawable);
                    }
                }
            });
}
 
Example 51
Project: ZhaZhaShop   File: MovieDetailActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void addRelatedMovie(List<RelatedMovieBean.DataBean> relatedMovies) {
    Observable.just(relatedMovies)
            .flatMap(new Function<List<RelatedMovieBean.DataBean>, ObservableSource<RelatedMovieBean.DataBean>>() {
                @Override
                public ObservableSource<RelatedMovieBean.DataBean> apply(@NonNull List<RelatedMovieBean.DataBean> dataBeen) throws Exception {
                    if (dataBeen.get(0).getItems().size() > 0) {
                        return Observable.just(dataBeen.get(0));
                    }
                    return Observable.error(new Exception("empty data"));
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<RelatedMovieBean.DataBean>() {
                @Override
                public void accept(@NonNull RelatedMovieBean.DataBean dataBean) throws Exception {
                    RelatedMovieAdapter relatedMovieAdapter = new RelatedMovieAdapter();
                    mRvRelatedMovie.setLayoutManager(new LinearLayoutManager(MovieDetailActivity.this, LinearLayoutManager.HORIZONTAL, false));
                    mRvRelatedMovie.setAdapter(relatedMovieAdapter);
                    relatedMovieAdapter.setNewData(dataBean.getItems());
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) throws Exception {
                    mLlRelatedMovie.setVisibility(View.GONE);
                }
            });
}
 
Example 52
Project: RxMapManager   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void useAMap() {
  RxMapManager.getInstance().init(new AMapStrategy() {
    @Override
    public AMapLocationClient initClient() {
      AMapLocationClientOption option = new AMapLocationClientOption();
      option.setNeedAddress(true);
      option.setInterval(5000);
      AMapLocationClient client = new AMapLocationClient(getBaseContext());
      client.setLocationOption(option);
      return client;
    }
  });

  //接收定位信息
  RxMapManager.getInstance().requestLocation()
      .subscribe(new Consumer<AMapLocation>() {
        @Override
        public void accept(AMapLocation o) throws Exception {
          if (o == null) {
            result.append("【接收定位信息】 null\n");
          } else {
            result.append("【接收定位信息】lat:" + o.getLatitude()
                + ",lng:" + o.getLongitude() + "\n");
          }
        }
      }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
          throwable.printStackTrace();
        }
      });
}
 
Example 53
Project: PartyBuildingStudies   File: StudiesPagePresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void onHandleParseHTML(final String url) {
    mView.setLoadingIndicator(true);
    Observable.create(new ObservableOnSubscribe<ArrayList<ArticleItem>>() {
        @Override
        public void subscribe(ObservableEmitter<ArrayList<ArticleItem>> e) throws Exception {
            ArrayList<ArticleItem> list = new ArrayList<>();
            Document doc = Jsoup.connect(url).get();
            Elements ul = doc.getElementsByClass("list_line");
            for (Element u : ul) {
                Elements li = u.getElementsByTag("li");
                for (Element l : li) {
                    String text = l.getElementsByTag("a").text();
                    String href = l.getElementsByTag("a").attr("href");
                    String time = l.getElementsByTag("span").text();
                    list.add(new ArticleItem(text, href, time));
                }
            }
            e.onNext(list);
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<ArrayList<ArticleItem>>() {
                @Override
                public void accept(@NonNull ArrayList<ArticleItem> articleItems) throws Exception {
                    mView.showList(articleItems);
                    mView.setLoadingIndicator(false);
                }
            });
}
 
Example 54
Project: YiZhi   File: BookCustomPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void loadLatestBookList() {
    if (mIModel == null || mIView == null)
        return;

    mStart = 0;
    //一次加载20条数据
    mRxManager.register(mIModel.getBookListWithTag(mIView.getBookTags(), mStart, mCount)
            .subscribe(new Consumer<BookListBean>() {
                @Override
                public void accept(BookListBean bookListBean) throws Exception {
                    if (mIView == null)
                        return;

                    mStart += mCount;
                    mIView.updateContentList(bookListBean.getBooks());
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    if (mIView == null)
                        return;

                    if (mIView.isVisiable())
                        mIView.showToast("Network error.");

                    mIView.showNetworkError();
                }
            }));
}
 
Example 55
Project: Rx_java2_soussidev   File: RxSharedPreferences_java.java   Source Code and License 5 votes vote down vote up
public Observable<String> putString(final String key, final String value) {
    return Observable.just(value)
            .doOnNext(new Consumer<String>() {
                @Override
                public void accept(@NonNull String v) throws Exception {
                    sharedPreferences.edit().putString(key, v).apply();
                }
            });
}
 
Example 56
Project: Weather-Guru-MVP   File: MainPresenter.java   Source Code and License 5 votes vote down vote up
@Override public void selectCity(CityDetailsModel city) {
  getCompositeDisposableHelper().addDisposable(getDataManager().selectCity(city, true)
      .compose(getCompositeDisposableHelper().<Boolean>applySchedulers())
      .subscribe(new Consumer<Boolean>() {
        @Override public void accept(Boolean aBoolean) throws Exception {
          getMvpView().onCitySelect();
          // refresh cities
          setDrawerCities();
        }
      }));
}
 
Example 57
Project: Layout_switch_RXshared_pref   File: RxSharedPreferences.java   Source Code and License 5 votes vote down vote up
public Observable<Float> putFloat(final String key, final Float value) {
    return Observable.just(value)
            .doOnNext(new Consumer<Float>() {
                @Override
                public void accept(@NonNull Float v) throws Exception {
                    sharedPreferences.edit().putFloat(key, v).apply();
                }
            });
}
 
Example 58
Project: rxtools   File: SubjectMap.java   Source Code and License 5 votes vote down vote up
/**
 * Emits the error from the observable associated with the specified key. After the
 * error is emitted, the observable will be automatically unbound, subsequent calls
 * to get will return a new observable and attempt to fault the value in
 *
 * @param key key with which the specified value is to be associated
 * @param error exception to be sent to the specified observable
 */
public void onError(K key, final Throwable error)
{
    emitUpdate(key, new Consumer<Processor<V, V>>() {
        @Override
        public void accept(Processor<V, V> subject)
        {
            subject.onError(error);
        }
    }, EMPTY_ACTION, true);
}
 
Example 59
Project: Rx_java2_soussidev   File: RxSharedPreferences_java.java   Source Code and License 5 votes vote down vote up
public Observable<Boolean> putBoolean(final String key, final Boolean value) {
    return Observable.just(value)
            .doOnNext(new Consumer<Boolean>() {
                @Override
                public void accept(@NonNull Boolean v) throws Exception {
                    sharedPreferences.edit().putBoolean(key, v).apply();
                }
            });
}
 
Example 60
Project: Rxjava2.0Demo   File: CreateActivity.java   Source Code and License 5 votes vote down vote up
private void skip() {
    Observable.just(1, 2, 3, 4, 5)
            .skip(2)
            .skipLast(2)
            .subscribe(new Consumer<Integer>() {
                @Override
                public void accept(Integer integer) throws Exception {
                    Log.e(TAG, "accept: " + integer);
                }
            });

}