java - Android 单个观察者,在不同的类中有多个订阅者

标签 java android retrofit rx-java observer-pattern

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

我尝试按照这个 awnser 进行操作,但出现了各种错误: Single Observable with Multiple Subscribers

目前情况如下:

GeofenceRetrofitEndpoint:

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

GeofenceDAO:

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); 时,它每次都会单独调用。谢谢

最佳答案

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

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

但要注意不要泄漏Obserable

关于java - Android 单个观察者,在不同的类中有多个订阅者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855631/

相关文章:

java - 同步工厂删除 sftp :inbound-channel-adapter 的文件夹

android - 我如何在没有初始化的情况下在 Kotlin 中声明一个可以从类中的任何 fun 访问的 val?

android - 未在 unity 中找到 android 设备

java - Android 和 Java 的 Retrofit REST 客户端不会终止

java - 尝试连接 JSON 服务器时出现异常

android - 应用程序在 HttpLoggingInterceptor 上崩溃

java - 子类和父类(super class)中的重复初始化

java - 如何在 Java Swing 中从第一帧开始生成 .gif 文件?

java - 如何在第一次构造字符串时定义 IntelliJ java 断点

java - 图像的错误 URL 编码