pull/32/head
Administrator 5 years ago
parent eea048dc70
commit ada677f03b
  1. 10
      app/src/main/java/io/legado/app/base/BaseViewModel.kt
  2. 2
      app/src/main/java/io/legado/app/help/permission/Request.kt
  3. 34
      app/src/main/java/io/legado/app/ui/search/SearchViewModel.kt

@ -4,6 +4,7 @@ import android.app.Application
import androidx.lifecycle.AndroidViewModel
import io.legado.app.help.coroutine.Coroutine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import org.jetbrains.anko.AnkoLogger
@ -11,10 +12,15 @@ import org.jetbrains.anko.AnkoLogger
open class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope by MainScope(),
AnkoLogger {
fun <T> execute(domain: suspend CoroutineScope.() -> T): Coroutine<T> {
return Coroutine.with(this) { domain() }
fun <T> execute(block: suspend CoroutineScope.() -> T): Coroutine<T> {
return Coroutine.with(this) { block() }
}
fun <T> submit(block: suspend CoroutineScope.() -> Deferred<T>): Coroutine<T> {
return Coroutine.with(this) { block().await() }
}
override fun onCleared() {
super.onCleared()
cancel()

@ -127,6 +127,7 @@ internal class Request : OnRequestPermissionsResultCallback {
private fun showSettingDialog(rationale: CharSequence, cancel: () -> Unit) {
rationaleDialog?.dismiss()
source?.context?.let {
runCatching {
rationaleDialog = AlertDialog.Builder(it)
.setTitle(R.string.dialog_title)
.setMessage(rationale)
@ -142,6 +143,7 @@ internal class Request : OnRequestPermissionsResultCallback {
.show()
}
}
}
private fun onPermissionsGranted(requestCode: Int) {
try {

@ -9,34 +9,44 @@ import io.legado.app.data.api.CommonHttpApi
import io.legado.app.data.entities.SearchBook
import io.legado.app.help.http.HttpHelper
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class SearchViewModel(application: Application) : BaseViewModel(application) {
val searchBooks: LiveData<List<SearchBook>> = MutableLiveData()
fun search(start: (() -> Unit)? = null, finally: (() -> Unit)? = null) {
execute {
val response: String = HttpHelper.getApiService<CommonHttpApi>(
"http://www.baidu.com"
).get("http://www.baidu.com").await()
launch {
delay(1000L)
delay(4000L)
Log.e("TAG1", Thread.currentThread().name)
repeat(100) {
test(it)
}
response
}
}
private fun test(index: Int) {
submit {
val response = HttpHelper.getApiService<CommonHttpApi>(
"http://www.baidu.com"
).get("http://www.baidu.com")
Log.e("TAG", "next: $index")
response
}
.timeout { 100L }
.onErrorReturn { "error return" }
.onStart {
Log.e("TAG!", "start")
Log.e("TAG!", "start: $index")
}
.onSuccess {
Log.e("TAG!", "success: $it")
Log.e("TAG!", "success: $index --> $it")
}
.onError {
Log.e("TAG!", "error: $it")
Log.e("TAG!", "error: $index --> $it")
}
.onFinally {
Log.e("TAG!", "finally")

Loading…
Cancel
Save