我有json响应["url1"、"url2"、"curl3"…"url10"]每个url都包含图像的地址。我用这个方法得到了这些网址的列表:
@GET("task-m-001/list.php")
fun getItems(): Single<List<String>>
10个url中有2个不起作用。我需要检查每个网址和过滤器破碎。
我的方法:
fun getItems(){
_networkState.postValue(NetworkState.LOADING)
try {
compositeDisposable.add(
apiService.getItems()
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.flatMapObservable { items ->
Observable.fromIterable(items)
.flatMap{
//Here i need to check urls... How to do that?
}
}
.toList()
.subscribe({ urlList ->
Log.i(TAG, "getItems: $urlList")
val itemsResponse = itemsResponseConverter.getItemResponse(urlList)
_downloadedItemsResponse.postValue(itemsResponse)
_networkState.postValue(NetworkState.LOADED)
},
{
Log.i(TAG, "Error - $it")
_networkState.postValue(NetworkState.ERROR)
})
)
}catch (e: Exception) {
Log.e(TAG, e.message.toString())
}
}
如何使用rxJava做到这一点?
首先尝试使用url和HttpURLConnection请求图像url并获取响应代码。如果图像有效,则响应代码将为200,否则无效
这是你现在的代码:
fun getItems(){
_networkState.postValue(NetworkState.LOADING)
try {
compositeDisposable.add(
apiService.getItems()
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.flatMapObservable { items ->
Observable.fromIterable(items)
.flatMap{
val url:URL = URL(imageUrl)
val http: HttpURLConnection: = url.openConnection() as HttpURLConnection
val statusCode: Integer = http.responseCode
return if(statusCode == 200) // correct image url
}
}
.toList()
.subscribe({ urlList ->
Log.i(TAG, "getItems: $urlList")
val itemsResponse = itemsResponseConverter.getItemResponse(urlList)
_downloadedItemsResponse.postValue(itemsResponse)
_networkState.postValue(NetworkState.LOADED)
},
{
Log.i(TAG, "Error - $it")
_networkState.postValue(NetworkState.ERROR)
})
)
}catch (e: Exception) {
Log.e(TAG, e.message.toString())
}
}