Always close requests' response body

This commit is contained in:
len 2016-05-26 15:16:42 +02:00
parent 6603c0b990
commit 79ec4faddb
2 changed files with 21 additions and 11 deletions

View File

@ -77,8 +77,8 @@ class MyAnimeList(private val context: Context, id: Int) : MangaSyncService(cont
} }
fun search(query: String): Observable<List<MangaSync>> { fun search(query: String): Observable<List<MangaSync>> {
return networkService.requestBody(get(getSearchUrl(query), headers)) return networkService.request(get(getSearchUrl(query), headers))
.map { Jsoup.parse(it) } .map { Jsoup.parse(it.body().string()) }
.flatMap { Observable.from(it.select("entry")) } .flatMap { Observable.from(it.select("entry")) }
.filter { it.select("type").text() != "Novel" } .filter { it.select("type").text() != "Novel" }
.map { .map {
@ -102,8 +102,8 @@ class MyAnimeList(private val context: Context, id: Int) : MangaSyncService(cont
// MAL doesn't support score with decimals // MAL doesn't support score with decimals
fun getList(): Observable<List<MangaSync>> { fun getList(): Observable<List<MangaSync>> {
return networkService.requestBody(get(getListUrl(username), headers), networkService.forceCacheClient) return networkService.request(get(getListUrl(username), headers), networkService.forceCacheClient)
.map { Jsoup.parse(it) } .map { Jsoup.parse(it.body().string()) }
.flatMap { Observable.from(it.select("manga")) } .flatMap { Observable.from(it.select("manga")) }
.map { .map {
val manga = MangaSync.create(this) val manga = MangaSync.create(this)

View File

@ -6,7 +6,9 @@ import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import okhttp3.Response import okhttp3.Response
import rx.Observable import rx.Observable
import rx.subscriptions.Subscriptions
import java.io.File import java.io.File
import java.io.IOException
class NetworkHelper(context: Context) { class NetworkHelper(context: Context) {
@ -39,14 +41,22 @@ class NetworkHelper(context: Context) {
get() = cookieManager.store get() = cookieManager.store
fun request(request: Request, client: OkHttpClient = defaultClient): Observable<Response> { fun request(request: Request, client: OkHttpClient = defaultClient): Observable<Response> {
return Observable.fromCallable { return Observable.create { subscriber ->
client.newCall(request).execute() val call = client.newCall(request)
} subscriber.add(Subscriptions.create { call.cancel() })
}
fun requestBody(request: Request, client: OkHttpClient = defaultClient): Observable<String> { try {
return Observable.fromCallable { val response = call.execute()
client.newCall(request).execute().body().string() if (!subscriber.isUnsubscribed) {
subscriber.add(Subscriptions.create { response.body().close() })
subscriber.onNext(response)
subscriber.onCompleted()
}
} catch (error: IOException) {
if (!subscriber.isUnsubscribed) {
subscriber.onError(error)
}
}
} }
} }