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. 在應用配置文件 app.php 中找不到’route_check_cache’配置項2. html按鍵開關如何提交我想需要的值到數據庫3. mysql取模分表與分表4. gvim - 誰有vim里CSS的Indent文件, 能縮進@media里面的5. HTML 5輸入框只能輸入漢字、字母、數字、標點符號?正則如何寫?6. 跟著課件一模一樣的操作使用tp6,出現了錯誤7. PHP類屬性聲明?8. objective-c - ios 怎么實現微信聯系列表 最好是swift9. javascript - 請教如何獲取百度貼吧新增的兩個加密參數10. java - 安卓接入微信登錄,onCreate不會執行
