RxJava flatMap使用

RxJava flatMap使用

1、使用场景
首先从一个接口中获取list,然后根据获取到list中的元素信息,再获取每个元素的详细信息
2、以下是代码片段(仅笔记于此)
String albumUrl = “http://m.kugou.com/zlist/list
?listid=2&type=0&uid=89255811
&sign=495dc043c2b3ac9f38e5f09d6d0bbef2
&_t=598024727&pagesize=100&json=&from=pcCode&page=1&share_type=collect”;
String musicPath = “D:\Music”; //表示存储路径
File file = new File(musicPath);
if (!file.exists()) {
file.mkdirs();
}
RxHttp.getInstance().getSyncServer()
.musicList(albumUrl)
.flatMap((Function<JSONObject, ObservableSource>) jsonObject -> {
List list = JSONObject.parseArray(jsonObject.getString(“info”), MusicItem.class);
return Observable.fromIterable(list);
})
.flatMap((Function<MusicItem, ObservableSource>) musicItem -> {
musicFile = new File(file.getAbsolutePath(), musicItem.getName() + “.mp3”);
return RxHttp.getInstance()
.getSyncServer()
.downloadMusic(musicItem);
})
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.subscribe(responseBody -> {
try {
InputStream is = responseBody.byteStream();
FileOutputStream fos = null;
fos = new FileOutputStream(musicFile);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
bis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
}
}, throwable -> {
System.out.print(throwable.getMessage());
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值