添加okhttp, retrofit配合协程使用

pull/31/head
Invinciblelee 6 years ago
parent b8bc0e8b59
commit 514dd5173a
  1. 22
      app/src/main/java/io/legado/app/base/BaseViewModel.kt
  2. 14
      app/src/main/java/io/legado/app/data/api/CommonHttpApi.kt
  3. 4
      app/src/main/java/io/legado/app/help/http/CoroutinesCallAdapterFactory.kt
  4. 15
      app/src/main/java/io/legado/app/help/http/HttpHelper.kt
  5. 25
      app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt

@ -13,13 +13,12 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
private val launchManager: MutableList<Job> = mutableListOf()
protected fun launchOnUI(
tryBlock: suspend CoroutineScope.() -> Unit,
cacheBlock: suspend CoroutineScope.(Throwable) -> Unit,
finallyBlock: suspend CoroutineScope.() -> Unit,
handleCancellationExceptionManually: Boolean
tryBlock: suspend CoroutineScope.() -> Unit,//成功
errorBlock: suspend CoroutineScope.(Throwable) -> Unit,//失败
finallyBlock: suspend CoroutineScope.() -> Unit//结束
) {
launchOnUI {
tryCatch(tryBlock, cacheBlock, finallyBlock, handleCancellationExceptionManually)
tryCatch(tryBlock, errorBlock, finallyBlock)
}
}
@ -27,25 +26,20 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
* add launch task to [launchManager]
*/
private fun launchOnUI(block: suspend CoroutineScope.() -> Unit) {
val job = launch { block() }
val job = launch { block() }//主线程
launchManager.add(job)
job.invokeOnCompletion { launchManager.remove(job) }
}
private suspend fun tryCatch(
tryBlock: suspend CoroutineScope.() -> Unit,
catchBlock: suspend CoroutineScope.(Throwable) -> Unit,
finallyBlock: suspend CoroutineScope.() -> Unit,
handleCancellationExceptionManually: Boolean = false
errorBlock: suspend CoroutineScope.(Throwable) -> Unit,
finallyBlock: suspend CoroutineScope.() -> Unit
) {
try {
coroutineScope { tryBlock() }
} catch (e: Throwable) {
if (e !is CancellationException || handleCancellationExceptionManually) {
coroutineScope { catchBlock(e) }
} else {
throw e
}
coroutineScope { errorBlock(e) }
} finally {
coroutineScope { finallyBlock() }
}

@ -0,0 +1,14 @@
package io.legado.app.data.api
import kotlinx.coroutines.Deferred
import retrofit2.http.*
interface CommonHttpApi {
@GET
fun get(@Url url: String, @QueryMap map: Map<String, String>): Deferred<String>
@FormUrlEncoded
@POST
fun post(@Url url: String, @FieldMap map: Map<String, String>): Deferred<String>
}

@ -6,10 +6,10 @@ import retrofit2.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class CoroutineCallAdapterFactory private constructor() : CallAdapter.Factory() {
class CoroutinesCallAdapterFactory private constructor() : CallAdapter.Factory() {
companion object {
@JvmStatic @JvmName("create")
operator fun invoke() = CoroutineCallAdapterFactory()
operator fun invoke() = CoroutinesCallAdapterFactory()
}
override fun get(

@ -1,6 +1,7 @@
package io.legado.app.help.http
import okhttp3.*
import retrofit2.Retrofit
import java.util.*
import java.util.concurrent.TimeUnit
@ -9,6 +10,20 @@ object HttpHelper {
val client: OkHttpClient = getOkHttpClient()
fun <T> getApiService(baseUrl: String, clazz: Class<T>): T {
return getRetrofit(baseUrl).create(clazz)
}
fun getRetrofit(baseUrl: String): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
//增加返回值为字符串的支持(以实体类返回)
// .addConverterFactory(EncodeConverter.create())
//增加返回值为Observable<T>的支持
.addCallAdapterFactory(CoroutinesCallAdapterFactory.invoke())
.client(client)
.build()
}
private fun getOkHttpClient(): OkHttpClient {
val cs = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)

@ -1,18 +1,39 @@
package io.legado.app.ui.search
import android.app.Application
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import io.legado.app.base.BaseViewModel
import io.legado.app.data.api.CommonHttpApi
import io.legado.app.data.entities.SearchBook
import io.legado.app.help.http.HttpHelper
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.withContext
class SearchViewModel(application: Application) : BaseViewModel(application){
class SearchViewModel(application: Application) : BaseViewModel(application) {
val searchBooks: LiveData<List<SearchBook>> = MutableLiveData()
public fun search(){
public fun search(start: () -> Unit, finally: () -> Unit) {
launchOnUI(
{
start()
val searchResponse = withContext(IO) {
HttpHelper.getApiService(
"http:www.baidu.com",
CommonHttpApi::class.java
).get("", mutableMapOf())
}
val result = searchResponse.await()
},
{ Log.i("TAG", "${it.message}") },
{ finally() })
// GlobalScope.launch {
//
// }
}
}

Loading…
Cancel
Save