android - RxJava中如何根據已有的函數或函數回調創建Observable?
問題描述
在使用Rxjava過程中,可能已經有很多函數回調,那么怎么根據這些函數回調的參數創建數據流?比如如果我需要改造onKeyDown(),那么怎么根據傳來按鍵的不同,處理特定用戶輸入的序列,比如用戶輸入“1,2,3,4”的時候做特殊處理。
或者有其他的函數回調,怎么將這些函數回調的數據使用bufferDebouncezip等操作符處理數據?
問題解答
回答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的回調,不方便再包裝一層,因此用了Subject這種可以【隨時隨地】發射數據、訂閱和發射方便分開寫的發射器。對于一般的回調可以這樣寫,給你個百度定位的回調感受一下
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();} }
對于一般的函數,可以這樣
Observable<String> o1 = Observable.fromCallable(new Callable<String>() { @Override public String call() {return func1(); }});public String func1(){ return 'ok';}
相關文章:
1. android - 請問一下 類似QQ音樂底部播放 在每個頁面都顯示 是怎么做的?2. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙3. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應用上有什么區別?4. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?5. python小白 關于類里面的方法獲取變量失敗的問題6. Python2中code.co_kwonlyargcount的等效寫法7. django - Python error: [Errno 99] Cannot assign requested address8. python小白,關于函數問題9. [python2]local variable referenced before assignment問題10. python - vscode 如何在控制臺輸入
