feat: 优化代码

pull/167/head
kunfei 5 years ago
parent 13ab8c35b8
commit ca67f585d1
  1. 3
      app/src/main/java/io/legado/app/help/coroutine/Coroutine.kt
  2. 18
      app/src/main/java/io/legado/app/ui/book/search/SearchViewModel.kt

@ -113,7 +113,7 @@ class Coroutine<T>(
fun cancel(cause: CancellationException? = null) {
job.cancel(cause)
cancel?.let {
scope.plus(Dispatchers.Main).launch {
MainScope().launch {
if (null == it.context) {
it.block.invoke(scope)
} else {
@ -177,6 +177,7 @@ class Coroutine<T>(
value: R,
callback: Callback<R>
) {
if (!scope.isActive) return
if (null == callback.context) {
callback.block.invoke(scope, value)
} else {

@ -12,8 +12,10 @@ import io.legado.app.help.coroutine.Coroutine
import io.legado.app.model.WebBook
import io.legado.app.utils.getPrefBoolean
import io.legado.app.utils.getPrefString
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.isActive
import java.util.concurrent.Executors
class SearchViewModel(application: Application) : BaseViewModel(application) {
@ -60,12 +62,14 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
)
.timeout(30000L)
.onSuccess(IO) {
if (isActive) {
it?.let { list ->
if (context.getPrefBoolean(PreferKey.precisionSearch)) {
precisionSearch(list)
precisionSearch(this, list)
} else {
App.db.searchBookDao().insert(*list.toTypedArray())
mergeItems(list)
mergeItems(this, list)
}
}
}
}
@ -86,7 +90,7 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
/**
* 精确搜索处理
*/
private fun precisionSearch(searchBooks: List<SearchBook>) {
private fun precisionSearch(scope: CoroutineScope, searchBooks: List<SearchBook>) {
val books = arrayListOf<SearchBook>()
searchBooks.forEach { searchBook ->
if (searchBook.name.contains(searchKey, true)
@ -94,14 +98,16 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
) books.add(searchBook)
}
App.db.searchBookDao().insert(*books.toTypedArray())
mergeItems(books)
if (scope.isActive) {
mergeItems(scope, books)
}
}
/**
* 合并搜索结果并排序
*/
@Synchronized
private fun mergeItems(newDataS: List<SearchBook>) {
private fun mergeItems(scope: CoroutineScope, newDataS: List<SearchBook>) {
if (newDataS.isNotEmpty()) {
val copyDataS = ArrayList(searchBooks)
val searchBooksAdd = ArrayList<SearchBook>()
@ -145,6 +151,7 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
}
}
}
if (!scope.isActive) return
searchBooks.sortWith(Comparator { o1, o2 ->
if (o1.name == searchKey && o2.name != searchKey) {
1
@ -170,6 +177,7 @@ class SearchViewModel(application: Application) : BaseViewModel(application) {
0
}
})
if (!scope.isActive) return
searchBooks = copyDataS
searchBookLiveData.postValue(copyDataS)
}

Loading…
Cancel
Save