我第一次尝试进入反应式编程。我正在使用适用于 Android 的ReactiveLocation库,并且我有 4 个文本视图需要在收到新位置时填充位置数据。
所以这是让我在每次位置更新时获得位置的代码:
locationProvider = new ReactiveLocationProvider(getApplicationContext());
lastKnownLocationObservable = locationProvider.getLastKnownLocation();
final LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setNumUpdates(150)
.setInterval(100);
locationUpdatesObservable = locationProvider
.checkLocationSettings(
new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
.setAlwaysShow(true) //Refrence: http://stackoverflow.com/questions/29824408/google-play-services-locationservices-api-new-option-never
.build()
)
.doOnNext(new Action1<LocationSettingsResult>() {
@Override
public void call(LocationSettingsResult locationSettingsResult) {
Status status = locationSettingsResult.getStatus();
if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
try {
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException th) {
Log.e("MainActivity", "Error opening settings activity.", th);
}
}
}
})
.flatMap(new Func1<LocationSettingsResult, Observable<Location>>() {
@Override
public Observable<Location> call(LocationSettingsResult locationSettingsResult) {
return locationProvider.getUpdatedLocation(locationRequest);
}
});
我也有这个 Func 将位置拆分为 4 个字符串的数组:
public class LocationToStringsArrayListFunc implements Func1<Location, ArrayList<String>> {
@Override
public ArrayList<String> call(Location location) {
ArrayList<String> locationDetails = null;
if (location != null) {
locationDetails = new ArrayList<>();
locationDetails.add(String.valueOf(location.getLatitude()));
locationDetails.add(String.valueOf(location.getLongitude()));
locationDetails.add(String.valueOf(location.getTime()));
locationDetails.add(String.valueOf(location.getSpeed()));
}
return locationDetails;
}
}
最后我有这个动作来用文本填充 TextView:
public class DisplayTextOnViewAction implements Action1<String> {
private final TextView target;
public DisplayTextOnViewAction(TextView target) {
this.target = target;
}
@Override
public void call(String s) {
target.setText(s);
}
}
我现在想要的是每次将此流拆分为 4 个视图,我知道对于一个视图,我将执行以下操作:
mUpdatableLocationSubscription = locationUpdatesObservable
.map(new LocationToStringsArrayListFunc())
.map(new Func1<ArrayList<String>, String>() {
@Override
public String call(ArrayList<String> stringArrayList) {
return stringArrayList.get(0);
}
})
.subscribe(new DisplayTextOnViewAction(tvLatitudeValue), new ErrorHandler());
如何使用相同的流填充其他 3 个 TextView:LongitudeValue、tvLastUpdateValue、tvSpeedValue?