pull/32/head
Invinciblelee 6 years ago
parent 926a2563f2
commit 565dd064c0
  1. 20
      app/src/main/java/io/legado/app/base/BaseViewModel.kt
  2. 10
      app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt

@ -4,33 +4,21 @@ import android.app.Application
import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.AndroidViewModel
import kotlinx.coroutines.* import kotlinx.coroutines.*
import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.AnkoLogger
import kotlin.coroutines.CoroutineContext
open class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope, AnkoLogger { open class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope by MainScope(),
override val coroutineContext: CoroutineContext AnkoLogger {
get() = Dispatchers.Main
private val launchManager: MutableList<Job> = mutableListOf()
protected fun launchOnUI( protected fun launchOnUI(
tryBlock: suspend CoroutineScope.() -> Unit, tryBlock: suspend CoroutineScope.() -> Unit,
errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null,//失败 errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null,//失败
finallyBlock: (suspend CoroutineScope.() -> Unit)? = null//结束 finallyBlock: (suspend CoroutineScope.() -> Unit)? = null//结束
) { ) {
launchOnUI { launch {
tryCatch(tryBlock, errorBlock, finallyBlock) tryCatch(tryBlock, errorBlock, finallyBlock)
} }
} }
/**
* add launch task to [launchManager]
*/
private fun launchOnUI(block: suspend CoroutineScope.() -> Unit) {
val job = launch { block() }//主线程
launchManager.add(job)
job.invokeOnCompletion { launchManager.remove(job) }
}
private suspend fun tryCatch( private suspend fun tryCatch(
tryBlock: suspend CoroutineScope.() -> Unit, tryBlock: suspend CoroutineScope.() -> Unit,
errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null, errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null,
@ -47,6 +35,6 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio
override fun onCleared() { override fun onCleared() {
super.onCleared() super.onCleared()
launchManager.clear() cancel()
} }
} }

@ -8,6 +8,8 @@ import io.legado.app.data.api.CommonHttpApi
import io.legado.app.data.entities.SearchBook import io.legado.app.data.entities.SearchBook
import io.legado.app.help.http.HttpHelper import io.legado.app.help.http.HttpHelper
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.jetbrains.anko.error import org.jetbrains.anko.error
@ -29,6 +31,14 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
}, },
{ error { "${it.message}" } }, { error { "${it.message}" } },
{ finally() }) { finally() })
launchOnUI({
//TODO
})
launch {
}
} }
} }

Loading…
Cancel
Save