好的,所以我正在尝试使用 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/