gpt4 book ai didi

android - 基于 Observable 的 API 和取消订阅问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:30 26 4
gpt4 key购买 nike

我正在尝试使用 Rx-Java 创建一个用于在 Android 上进行位置跟踪的类。我仍然无法弄清楚的是如何正确处理我的 Observable 的生命周期。我想要的是一个 Observable,它在第一次订阅发生时开始跟踪位置,并在最后一个订阅被丢弃时停止位置跟踪。到目前为止,我取得的成就是:

public class LocationObservable 
implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {

private LocationClient locationClient;
private final PublishSubject<Location> latestLocation =
PublishSubject.create();
public final Observable<Location> locationObservable =
Observable.defer(() -> {
if(!locationClient.isConnected() && !locationClient.isConnecting()) {
locationClient.connect();
}
return latestLocation.asObservable().scan((prev, curr) -> {
if (Math.abs(prev.getLatitude() - curr.getLatitude()) > 0.000001 ||
Math.abs(prev.getLongitude() - curr.getLongitude()) > 0.000001)
return curr;
else
return prev;
}).distinctUntilChanged();});

public LocationObservable(Context context) {

locationClient = new LocationClient(context, this, this);
}

@Override
public void onConnected(Bundle bundle) {
latestLocation.onNext(locationClient.getLastLocation());
}

@Override
public void onDisconnected() {
latestLocation.onCompleted();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
latestLocation.onError(new Exception(connectionResult.toString()));
}

@Override
public void onLocationChanged(Location location) {
latestLocation.onNext(location);
}
}

如您所见,我使用 Observable#defer 在第一个客户端订阅时初始化位置回调。我不知道这是否是一个好方法,但这是我目前想到的最好方法。我仍然缺少的是当我类(class)的最后一个客户取消订阅我的 Observable 时如何停止位置更新。或者它可能是 Rx 中的一些非惯用的东西,因为它不明显?

我相信,这个用例应该是相当标准的,因此应该有一个标准/惯用的解决方案。很高兴知道。

最佳答案

private LocationClient locationClient;
private final Observable<Integer> locationObservable = Observable
.create(new OnSubscribe<Integer>() {

@Override
public void call(Subscriber<? super Integer> subscriber) {
locationClient.connect();
subscriber.add(Subscriptions.create(new Action0() {

@Override
public void call() {
if (locationClient.isConnected()
|| locationClient.isConnecting()) {
locationClient.disconnect();
}
}

}));
}

}).multicast(PublishSubject.<Integer> create()).refCount();

关于android - 基于 Observable 的 API 和取消订阅问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22131779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com