Parallelize global search properly

Fixes #8906
This commit is contained in:
arkon 2023-01-13 17:58:00 -05:00
parent a2ee4e63ae
commit 91004ad514

View File

@ -19,6 +19,8 @@ import eu.kanade.tachiyomi.util.lang.withIOContext
import eu.kanade.tachiyomi.util.lang.withNonCancellableContext import eu.kanade.tachiyomi.util.lang.withNonCancellableContext
import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@ -133,22 +135,17 @@ abstract class SearchScreenModel<T>(
updateItems(initialItems) updateItems(initialItems)
coroutineScope.launch { coroutineScope.launch {
sources.forEach { source -> sources
val page = try { .map { source ->
withContext(coroutineDispatcher) { async {
try {
val page = withContext(coroutineDispatcher) {
logcat { "Searching ${source.name}" }
source.fetchSearchManga(1, query, source.getFilterList()).awaitSingle() source.fetchSearchManga(1, query, source.getFilterList()).awaitSingle()
} }
} catch (e: Exception) {
getAndUpdateItems { items ->
val mutableMap = items.toMutableMap()
mutableMap[source] = SearchItemResult.Error(throwable = e)
mutableMap.toSortedMap(sortComparator(mutableMap))
}
return@forEach
}
val titles = page.mangas.map { val titles = withIOContext {
withIOContext { page.mangas.map {
networkToLocalManga.await(it.toDomainManga(source.id)) networkToLocalManga.await(it.toDomainManga(source.id))
} }
} }
@ -158,10 +155,19 @@ abstract class SearchScreenModel<T>(
mutableMap[source] = SearchItemResult.Success(titles) mutableMap[source] = SearchItemResult.Success(titles)
mutableMap.toSortedMap(sortComparator(mutableMap)) mutableMap.toSortedMap(sortComparator(mutableMap))
} }
} catch (e: Exception) {
getAndUpdateItems { items ->
val mutableMap = items.toMutableMap()
mutableMap[source] = SearchItemResult.Error(throwable = e)
mutableMap.toSortedMap(sortComparator(mutableMap))
} }
} }
} }
} }
.awaitAll()
}
}
}
sealed class SearchItemResult { sealed class SearchItemResult {
object Loading : SearchItemResult() object Loading : SearchItemResult()