android - How to create an Observable based on an existing function or function callback in RxJava?
怪我咯
怪我咯 2017-05-16 13:28:50
0
1
651

In the process of using Rxjava, there may already be many function callbacks, so how to create a data stream based on the parameters of these function callbacks?
For example, if I need to modify onKeyDown(), how can I process a specific sequence of user input according to the different keystrokes, such as special processing when the user inputs "1, 2, 3, 4".

Or if there are other function callbacks, how to use operators such as bufferDebouncezip to process the data of these function callbacks?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all (1)
大家讲道理

You can write like this

private BehaviorSubject bs; private void testSeri() { bs = BehaviorSubject.create(); //每3次 accept 一次 bs.buffer(3) .subscribe(new Consumer>() { @Override public void accept(@NonNull List 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 is the callback of Activity. It is inconvenient to wrap it in another layer, so we use Subject, which can transmit data [anytime and anywhere], subscribe and transmit easily and write separately. For general callbacks, you can write it like this. Let me give you a feel for the callbacks positioned by Baidu

class LocationObservable implements ObservableOnSubscribe { @Override public void subscribe(final ObservableEmitter e) throws Exception { initLocation(); mLocationClient.registerLocationListener( new BDLocationListener(){ @Override public 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(); } }

For general functions, you can do this

Observable o1 = Observable.fromCallable(new Callable() { @Override public String call() { return func1(); } }); public String func1(){ return "ok"; }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!