perf: lazy load

This commit is contained in:
lisonge 2024-05-13 12:32:02 +08:00
parent b0627a3b18
commit efa1829a39
2 changed files with 20 additions and 8 deletions

View File

@ -21,6 +21,9 @@ data class AppInfo(
val hidden: Boolean,
)
/**
* 平均单次调用时间 11ms
*/
fun PackageInfo.toAppInfo(): AppInfo? {
applicationInfo ?: return null
return AppInfo(

View File

@ -6,6 +6,8 @@ import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import com.blankj.utilcode.util.LogUtils
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toImmutableMap
import kotlinx.coroutines.Dispatchers
@ -18,17 +20,22 @@ import li.songe.gkd.appScope
import li.songe.gkd.data.AppInfo
import li.songe.gkd.data.toAppInfo
val appInfoCacheFlow = MutableStateFlow(emptyMap<String, AppInfo>().toImmutableMap())
val appInfoCacheFlow = MutableStateFlow(persistentMapOf<String, AppInfo>().toImmutableMap())
val systemAppInfoCacheFlow =
appInfoCacheFlow.map(appScope) { c -> c.filter { a -> a.value.isSystem }.toImmutableMap() }
val systemAppInfoCacheFlow by lazy {
appInfoCacheFlow.map(appScope) { c ->
c.filter { a -> a.value.isSystem }.toImmutableMap()
}
}
val systemAppsFlow = systemAppInfoCacheFlow.map(appScope) { c -> c.keys }
val systemAppsFlow by lazy { systemAppInfoCacheFlow.map(appScope) { c -> c.keys } }
val orderedAppInfosFlow = appInfoCacheFlow.map(appScope) { c ->
c.values.sortedWith { a, b ->
collator.compare(a.name, b.name)
}.toImmutableList()
val orderedAppInfosFlow by lazy {
appInfoCacheFlow.map(appScope) { c ->
c.values.sortedWith { a, b ->
collator.compare(a.name, b.name)
}.toImmutableList()
}
}
private val packageReceiver by lazy {
@ -94,6 +101,7 @@ val appRefreshingFlow = MutableStateFlow(false)
suspend fun initOrResetAppInfoCache() {
if (updateAppMutex.isLocked) return
LogUtils.d("initOrResetAppInfoCache start")
appRefreshingFlow.value = true
updateAppMutex.withLock {
val oldAppIds = appInfoCacheFlow.value.keys
@ -111,6 +119,7 @@ suspend fun initOrResetAppInfoCache() {
appInfoCacheFlow.value = appMap.toImmutableMap()
}
appRefreshingFlow.value = false
LogUtils.d("initOrResetAppInfoCache end")
}
fun initAppState() {