Rxjava+Retrofit使用心得
一、Rxjava+Retrofit的包依赖
//RxJava
implementation "io.reactivex.rxjava2:rxjava:2.1.0"
implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
二、Rxjava+Retrofit的使用
<!--相关权限-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
/**
* 创建日期:2020/5/27 0027
*
* @author :Gentle Wen
* describe:
*/
public class MainViewModel extends BaseViewModel {
private final Retrofit retrofit;
private String TAG = getClass().getSimpleName();
public MainViewModel() {
retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://xxx.xxx.xx/api")
.build();
}
@SuppressLint("CheckResult")
public void getApiService() {
ApiService apiService = retrofit.create(ApiService.class);
apiService.getApiResponse(new MainParams())
.subscribeOn(Schedulers.io())
.flatMap(new Function<MainResponse, ObservableSource<MainData>>() {
@Override
public ObservableSource<MainData> apply(MainResponse response){
Log.i(TAG, "apply: "+"加载到了Response:"+response.toString());
return Observable.fromIterable(response.getDataInfo());
}
})
.flatMap(new Function<MainData, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(MainData mainData) {
Log.i(TAG, "apply: "+"加载每个Data:"+mainData.toString());
Log.i(TAG, "apply: "+"servicePic:"+mainData.getServicePic());
String servicePic = mainData.getServicePic();
String[] urls = servicePic.split("#");
return Observable.fromIterable(Arrays.asList(urls));
}
})
.map(new Function<String, Bitmap>() {
@Override
public Bitmap apply(String s) throws Exception {
Log.i(TAG, "apply: "+"加载图片:"+s);
URL url = new URL(s);
HttpURLConnection httpURLConnection
= (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10 * 1000);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
return null;
}
})
.map(new Function<Bitmap, Bitmap>() {
@Override
public Bitmap apply(Bitmap bitmap) throws Exception {
String dirName = "Rxjava";
String imageName = System.currentTimeMillis()+".png";
String imageFilePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/"+dirName;
File bitmapDir= new File(imageFilePath);
if (bitmapDir.exists()){
Log.i(TAG, "apply: "+bitmapDir.getPath()+"文件已存在");
}else {
bitmapDir.mkdir();
Log.i(TAG, "apply: "+"创建文件夹"+bitmapDir.getPath());
}
File imageFile = new File(bitmapDir.getPath()+"/"+imageName);
if (!imageFile.exists()){
imageFile.createNewFile();
}
FileOutputStream fileOutputStream
= new FileOutputStream(imageFile);
try {
bitmap.compress(
Bitmap.CompressFormat.PNG
, 100
,fileOutputStream);
Log.i(TAG, "apply: 保存成功:"+imageFile.getPath());
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "apply: 保存失败");
}finally {
fileOutputStream.flush();
fileOutputStream.close();
}
return bitmap;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Bitmap>() {
@Override
public void onSubscribe(Disposable d) {
Log.i(TAG, "onSubscribe: ");
}
@Override
public void onNext(Bitmap bitmap) {
Log.i(TAG, "onNext: " + bitmap);
}
@Override
public void onError(Throwable e) {
Log.i(TAG, "onError: "+e.getMessage());
}
@Override
public void onComplete() {
Log.i(TAG, "onComplete: ");
}
});
}
}
三、结果显示
I/MainViewModel: onSubscribe:
I/MainViewModel: apply: 加载到了Response:PublicResponse
I/MainViewModel: apply: 加载每个Data:MainData
I/MainViewModel: apply: servicePic:http://xxx.xxx.xx/upload/1548062920491shi887jian.jpg
I/MainViewModel: apply: 加载图片:http://xxx.xxx.xx/upload/1548062920491shi887jian.jpg
I/MainViewModel: apply: /storage/sdcard0/Rxjava文件已存在
I/MainViewModel: apply: 保存成功:/storage/sdcard0/Rxjava/1590566231417.png
I/MainViewModel: apply: 加载每个Data:MainData
I/MainViewModel: onNext: android.graphics.Bitmap@30770e1c
I/MainViewModel: apply: servicePic:http://xxx.xxx.xx/upload/1585015823125shi58jian.jpg
I/MainViewModel: apply: 加载图片:http://xxx.xxx.xx/upload/1585015823125shi58jian.jpg
I/MainViewModel: apply: /storage/sdcard0/Rxjava文件已存在
I/MainViewModel: apply: 保存成功:/storage/sdcard0/Rxjava/1590566231787.png
I/MainViewModel: onNext: android.graphics.Bitmap@2ea5ba25
/MainViewModel: onComplete:
四、总结
Rxjava强大的框架令人叹为观止,但是Rxjava最强大的地方并不是如何去使用,而是他的Rx思想,从而衍生出各种Rx相关的框架比如(RxView..),配合Retrofit使用这个是真的香啊。