我正在制作一个 android 应用程序,如果它是第一次调用 api 调用,则尝试将地图标记添加到地图中,或者只是重新设置标记的位置。我正在使用 RxJava2 重复调用 API。问题是我无法检查它是否是第一个 API 调用,因为我无法访问非最终布尔值。
boolean firstReposition = true;
//Create position call
ISSPositionService service = ServiceGenerator.createService(ISSPositionService.class);
//create observable
Observable<ISSPositionData> issPositionCall = service.getPosition();
Disposable disposable = issPositionCall.subscribeOn(Schedulers.io())
.repeatWhen(completed -> completed.delay(30, java.util.concurrent.TimeUnit.SECONDS))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(positionData -> {
LatLng currentIssPosition = new LatLng(positionData.getIssPosition().getLatitude(), positionData.getIssPosition().getLongitude());
if (firstReposition) {
issMarkerOptions.position(currentIssPosition);
map.addMarker(issMarkerOptions);
firstReposition = false;
}
else {
issMarker.setPosition(currentIssPosition);
}
//animate camera so it shows current position
map.animateCamera(CameraUpdateFactory.newLatLng(currentIssPosition));
});
我将如何重写代码以便能够检查和设置布尔值?
使用AtomicBoolean
,可以使用set()
和get()
方法 java-docs
AtomicBoolean firstReposition = new AtomicBoolean(true);
//Create position call
ISSPositionService service = ServiceGenerator.createService(ISSPositionService.class);
//create observable
Observable<ISSPositionData> issPositionCall = service.getPosition();
Disposable disposable = issPositionCall.subscribeOn(Schedulers.io())
.repeatWhen(completed -> completed.delay(30, java.util.concurrent.TimeUnit.SECONDS))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(positionData -> {
LatLng currentIssPosition = new LatLng(positionData.getIssPosition().getLatitude(), positionData.getIssPosition().getLongitude());
if (firstReposition) {
issMarkerOptions.position(currentIssPosition);
map.addMarker(issMarkerOptions);
firstReposition.set(false);
}
else {
issMarker.setPosition(currentIssPosition);
}
//animate camera so it shows current position
map.animateCamera(CameraUpdateFactory.newLatLng(currentIssPosition));
});