Use async method for network calls, trying to fix a crash

This commit is contained in:
len 2016-05-27 13:56:18 +02:00
parent 0fe350af9a
commit 79bb207a8d

View file

@ -1,12 +1,10 @@
package eu.kanade.tachiyomi.data.network package eu.kanade.tachiyomi.data.network
import android.content.Context import android.content.Context
import okhttp3.Cache import okhttp3.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable import rx.Observable
import rx.subscriptions.Subscriptions import rx.subscriptions.Subscriptions
import timber.log.Timber
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
@ -43,20 +41,30 @@ class NetworkHelper(context: Context) {
fun request(request: Request, client: OkHttpClient = defaultClient): Observable<Response> { fun request(request: Request, client: OkHttpClient = defaultClient): Observable<Response> {
return Observable.create { subscriber -> return Observable.create { subscriber ->
val call = client.newCall(request) val call = client.newCall(request)
subscriber.add(Subscriptions.create { call.cancel() }) subscriber.add(Subscriptions.create {
call.cancel()
Timber.i("Cancel call on thread ${Thread.currentThread().id}")
})
try { call.enqueue(object : Callback {
val response = call.execute() override fun onResponse(call: Call, response: Response) {
if (!subscriber.isUnsubscribed) { if (!subscriber.isUnsubscribed) {
subscriber.add(Subscriptions.create { response.body().close() }) subscriber.add(Subscriptions.create {
subscriber.onNext(response) response.body().close()
subscriber.onCompleted() Timber.i("Close body on thread ${Thread.currentThread().id}")
})
subscriber.onNext(response)
Timber.i("Emit response on thread ${Thread.currentThread().id}")
subscriber.onCompleted()
}
} }
} catch (error: IOException) {
if (!subscriber.isUnsubscribed) { override fun onFailure(call: Call, error: IOException) {
subscriber.onError(error) if (!subscriber.isUnsubscribed) {
subscriber.onError(error)
}
} }
} })
} }
} }