接下来看看如何在Presenter中应用RxJava、RxAndroid获取数据
//获取天气数据
@Override
public void getWeatherData(String place) {
if (TextUtils.isEmpty(place)) {
return;
}
mMainView.showProgress();
ServiceManager.getInstance().getApiService().getWeatherInfo(place, Constants.BAIDU_AK)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<WeatherResponse>() {
@Override
public void onCompleted() {
Log.e(TAG, "onCompleted");
mMainView.hideProgress();
}
@Override
public void onError(Throwable e) {
Log.e(TAG, e.getMessage(), e);
mMainView.hideProgress();
}
@Override
public void onNext(WeatherResponse weatherResponse) {
mMainView.setupWeatherData(weatherResponse);
}
});
}
public interface ApiService {
/*@GET("service/getIpInfo.php")
Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);*/
@GET("service/getIpInfo.php")
Observable<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);
//http://www.easck.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=MPDgj92wUYvRmyaUdQs1XwCf
@GET("/telematics/v3/weather?output=json")
Observable<WeatherResponse> getWeatherInfo(@Query("location") String location, @Query("ak") String ak);
}
如上所述,我们通过百度api获取天气数据使用的是Retrofit框架,它能自动的返回Observable对象。
那么我们如何通过RxJava获取本地文件中的城市列表呢?(为了方便演示,我将城市列表作为一个json字符串放于文件中)
@Override
public void getPlaceData() {
PlaceRepository repository = new PlaceRepository();
repository.getPlaceList(BaseApplication.getInstance())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Place>>() {
@Override
public void onNext(List<Place> places) {
mMainView.setupPlaceData(places);
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
});
}
public class PlaceRepository {
public Observable<List<Place>> getPlaceList(final Context context) {
return Observable.create(new Observable.OnSubscribe<List<Place>>() {
@Override
public void call(Subscriber<? super List<Place>> subscriber) {
try {
AssetManager assertManager = context.getAssets();
InputStream inputStream = assertManager.open("place");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while((count = inputStream.read(data,0, 1024)) != -1) {
outStream.write(data, 0, count);
}
String json = new String(outStream.toByteArray(),"UTF-8");
Gson gson = new GsonBuilder().create();
List<Place> placeList = gson.fromJson(json, new TypeToken<List<Place>>() {}.getType());
subscriber.onNext(placeList);
} catch (Exception e) {
subscriber.onError(e);
}
subscriber.onCompleted();
}
});
}
}










