RxJava / RxAndroid - 来自传感器的无限事件流

时间:2016-02-24 20:05:06

标签: android rx-java reactive-programming rx-android

我有一个应用程序监视传感器的事件,转换它们并需要向上游推送到订阅者。

例如,使用android.location.LocationManager进行位置更改。转换可能包括使用原始lat/longGeoCoder来获取Address

如何为我的显示器(LocationListener)和发布商建模?

class MyLocationListener implements LocationListener {
    void onLocationChanged(Location l) {
        //Get Address using GeoCoder
    }
}


class MetaAPI {
    Observable<Address> address() {
        return Observable.create({what}); //<-- What should I add here?
        //Need to glue MyLocationManager and MetaAPI
    }
}

//So that I can use like this -->
public AddressObservation {
    void monitor() {
        metaApi.address()
            .subscribe(...)
            ...;
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用Subject来实现此目的。这只是主要想法,没有任何设计考虑因素(根据您的需要调整您的情况):

class MyLocationListener implements LocationListener {
    void onLocationChanged(Location l) {
        //Get Address using GeoCoder
        MetaAPI.subject.onNext(null /* actual address object */);
    }
}

class MetaAPI {

    static Subject<Address, Address> subject = PublishSubject.<Address>create().toSerialized();

    Observable<Address> address() {
        return subject;
    }
}