【问题标题】:Android Single observer with multiple subscribers in separate classesAndroid 单个观察者,在不同的类中有多个订阅者
【发布时间】:2017-03-17 10:53:58
【问题描述】:

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

我尝试关注这个 awnser,但我得到了各种各样的错误: Single Observable with Multiple Subscribers

目前情况如下:

GeofenceRetrofitEndpoint:

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

地理围栏DAO:

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();
    }
}

MapFragment / 我需要结果的任何其他类

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); 时,它每次都在做一个单独的电话。谢谢

【问题讨论】:

    标签: java android retrofit rx-java observer-pattern


    【解决方案1】:

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

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

    但注意不要泄露Obserable

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2018-06-11
        • 2016-06-26
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        相关资源
        最近更新 更多