android - RxJava中如何根據(jù)已有的函數(shù)或函數(shù)回調(diào)創(chuàng)建Observable?
問題描述
在使用Rxjava過程中,可能已經(jīng)有很多函數(shù)回調(diào),那么怎么根據(jù)這些函數(shù)回調(diào)的參數(shù)創(chuàng)建數(shù)據(jù)流?比如如果我需要改造onKeyDown(),那么怎么根據(jù)傳來按鍵的不同,處理特定用戶輸入的序列,比如用戶輸入“1,2,3,4”的時(shí)候做特殊處理。
或者有其他的函數(shù)回調(diào),怎么將這些函數(shù)回調(diào)的數(shù)據(jù)使用bufferDebouncezip等操作符處理數(shù)據(jù)?
問題解答
回答1:可以這樣寫
private BehaviorSubject<Integer> bs; private void testSeri() {bs = BehaviorSubject.create();//每3次 accept 一次bs.buffer(3).subscribe(new Consumer<List<Integer>>() { @Override public void accept(@NonNull List<Integer> ints) throws Exception {StringBuilder sb = new StringBuilder();for (int i = 0; i < ints.size(); i++){ sb.append(ints.get(0));}Toast.makeText(TestSubjectActivity.this, sb.toString(), Toast.LENGTH_SHORT).show(); }}); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) {bs.onNext(keyCode);return super.onKeyDown(keyCode, event); }
onKeyDown是Activity的回調(diào),不方便再包裝一層,因此用了Subject這種可以【隨時(shí)隨地】發(fā)射數(shù)據(jù)、訂閱和發(fā)射方便分開寫的發(fā)射器。對(duì)于一般的回調(diào)可以這樣寫,給你個(gè)百度定位的回調(diào)感受一下
class LocationObservable implements ObservableOnSubscribe<BDLocation> {@Overridepublic void subscribe(final ObservableEmitter<BDLocation> e) throws Exception { initLocation(); mLocationClient.registerLocationListener( new BDLocationListener(){@Overridepublic void onReceiveLocation(BDLocation location) { if (location != null) {mLocationClient.stop();if (!TextUtils.isEmpty(location.getCity())) { e.onNext(location); e.onComplete();} } else {// 定位失敗e.onError(new Exception('百度地圖 定位失敗')); }} } ); mLocationClient.start();} }
對(duì)于一般的函數(shù),可以這樣
Observable<String> o1 = Observable.fromCallable(new Callable<String>() { @Override public String call() {return func1(); }});public String func1(){ return 'ok';}
相關(guān)文章:
1. python - 如何統(tǒng)計(jì)一份英文 API 開發(fā)文檔(如 javadoc文檔)的詞頻?2. mysql優(yōu)化 - mysql 一張表如果不能確保字段列長(zhǎng)度一致,是不是就不需要用到char。3. python - oslo_config4. 請(qǐng)教一個(gè)mysql去重取最新記錄5. python - 請(qǐng)問這兩個(gè)地方是為什么呢?6. python - 為什么match匹配出來的結(jié)果是<_sre.SRE_Match object; span=(0, 54), match=’’>7. javascript - 按鈕鏈接到另一個(gè)網(wǎng)址 怎么通過百度統(tǒng)計(jì)計(jì)算按鈕的點(diǎn)擊數(shù)量8. 人工智能 - python 機(jī)器學(xué)習(xí) 醫(yī)療數(shù)據(jù) 怎么學(xué)9. php - 有關(guān)sql語句反向LIKE的處理10. 大家都用什么工具管理mysql數(shù)據(jù)庫?
