Android 单个观察者,在单独的类中具有多个订阅者



好的,所以我正在尝试使用retrofit2实现rxJava2。目标是只进行一次调用,并将结果广播到不同的类。例如:我的后端有一个地理围栏列表。我需要 MapFragment 中的该列表在地图上显示它们,但我还需要该数据来为实际触发器设置挂起的意图服务。

我尝试遵循这个awnser,但我收到各种错误:具有多个订阅者的单个可观察对象

目前的情况如下:

GeofenceRetrofitEndpoint:

public interface GeofenceEndpoint {
    @GET("geofences")
    Observable<List<Point>> getGeofenceAreas();
}

地理围栏道:

public class GeofenceDao {
    @Inject
    Retrofit retrofit;
    private final GeofenceEndpoint geofenceEndpoint;
    public GeofenceDao(){
        InjectHelper.getRootComponent().inject(this);
        geofenceEndpoint = retrofit.create(GeofenceEndpoint.class);
    }
    public Observable<List<Point>> loadGeofences() {
        return geofenceEndpoint.getGeofenceAreas().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .share();
    }
}

地图片段/我需要结果的任何其他类

private void getGeofences() {
    new GeofenceDao().loadGeofences().subscribe(this::handleGeoResponse, this::handleGeoError);
}
private void handleGeoResponse(List<Point> points) {
    // handle response
}
private void handleGeoError(Throwable error) {
    // handle error
}

我做错了什么,因为当我打电话给new GeofenceDao().loadGeofences().subscribe(this::handleGeoResponse, this::handleGeoError);时,它每次都在做一个单独的电话。感谢

new GeofenceDao().loadGeofences()返回Observable的两个不同实例。 share()仅适用于实例,不适用于方法。如果要实际共享可观察量,则必须订阅同一实例。您可以与(静态(成员loadGeofences共享它。

private void getGeofences() {
    if (loadGeofences == null) {
        loadGeofences = new GeofenceDao().loadGeofences();
    }
    loadGeofences.subscribe(this::handleGeoResponse, this::handleGeoError);
}

但要小心不要泄露Obserable

也许它没有直接回答你的问题,但是我想建议你一个不同的方法:

在您的GeofenceDao中创建BehaviourSubject,并订阅此主题的改造请求。此主题将充当客户端和 API 之间的桥梁,通过这样做,您将获得:

  1. 响应缓存 - 方便屏幕旋转
  2. 为每个感兴趣的观察者重播响应
  3. 客户端和主体
  4. 之间的订阅不依赖于主体和 API 之间的订阅,因此您可以在不破坏另一个的情况下中断一个

最新更新