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

RxJava/RxAndroid - Infinite Stream of Events from Sensors

我有一个应用程序可以监控事件传感器、转换它们并需要向上游推送给订阅者。

例如,使用 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(...)
            ...;
    }
}

您可以使用 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;
    }
}