diff --git a/app/src/main/java/io/legado/app/base/BaseViewModel.kt b/app/src/main/java/io/legado/app/base/BaseViewModel.kt index c647b34bd..852e99166 100644 --- a/app/src/main/java/io/legado/app/base/BaseViewModel.kt +++ b/app/src/main/java/io/legado/app/base/BaseViewModel.kt @@ -4,33 +4,21 @@ import android.app.Application import androidx.lifecycle.AndroidViewModel import kotlinx.coroutines.* import org.jetbrains.anko.AnkoLogger -import kotlin.coroutines.CoroutineContext -open class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope, AnkoLogger { - override val coroutineContext: CoroutineContext - get() = Dispatchers.Main +open class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope by MainScope(), + AnkoLogger { - private val launchManager: MutableList = mutableListOf() protected fun launchOnUI( tryBlock: suspend CoroutineScope.() -> Unit, errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null,//失败 finallyBlock: (suspend CoroutineScope.() -> Unit)? = null//结束 ) { - launchOnUI { + launch { 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( tryBlock: suspend CoroutineScope.() -> Unit, errorBlock: (suspend CoroutineScope.(Throwable) -> Unit)? = null, @@ -47,6 +35,6 @@ open class BaseViewModel(application: Application) : AndroidViewModel(applicatio override fun onCleared() { super.onCleared() - launchManager.clear() + cancel() } } \ No newline at end of file diff --git a/app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt b/app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt index a1ea4039d..649df0c09 100644 --- a/app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt +++ b/app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt @@ -8,6 +8,8 @@ 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.coroutineScope +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.anko.error @@ -29,6 +31,14 @@ class SearchViewModel(application: Application) : BaseViewModel(application) { }, { error { "${it.message}" } }, { finally() }) + + launchOnUI({ + //TODO + }) + + launch { + + } } }