Skip to content

Commit

Permalink
优化代码
Browse files Browse the repository at this point in the history
在 MutableState 设置值的地方都使用 Dispatchers.Main 调度
  • Loading branch information
aaa1115910 committed Dec 27, 2024
1 parent cc0fa67 commit 47aff9c
Show file tree
Hide file tree
Showing 25 changed files with 195 additions and 134 deletions.
14 changes: 9 additions & 5 deletions app/src/main/kotlin/dev/aaa1115910/bv/screen/SeasonInfoScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,17 @@ fun SeasonInfoScreen(
val updateSeasonData: (seasonId: Int?, epId: Int?) -> Unit = { sId, eId ->
scope.launch(Dispatchers.IO) {
runCatching {
seasonData = videoDetailRepository.getPgcVideoDetail(
val data = videoDetailRepository.getPgcVideoDetail(
seasonId = sId,
epid = eId,
preferApiType = if (proxyArea != ProxyArea.MainLand) ApiType.App else Prefs.apiType
)
logger.info { "User status: ${seasonData!!.userStatus}" }
isFollowing = seasonData!!.userStatus.follow
lastPlayProgress = seasonData!!.userStatus.progress
withContext(Dispatchers.Main) {
seasonData = data
logger.info { "User status: ${seasonData!!.userStatus}" }
isFollowing = seasonData!!.userStatus.follow
lastPlayProgress = seasonData!!.userStatus.progress
}
}.onFailure {
tip = it.localizedMessage ?: "未知错误"
logger.fInfo { "Get season info failed: ${it.stackTraceToString()}" }
Expand All @@ -198,11 +201,12 @@ fun SeasonInfoScreen(
//延迟 200ms,避免获取到的依旧是旧数据
delay(200)
runCatching {
lastPlayProgress = videoDetailRepository.getPgcVideoDetail(
val data = videoDetailRepository.getPgcVideoDetail(
seasonId = seasonId,
epid = epId,
preferApiType = if (proxyArea != ProxyArea.MainLand) ApiType.App else Prefs.apiType
).userStatus.progress
withContext(Dispatchers.Main) { lastPlayProgress = data }
logger.info { "update user status progress: $lastPlayProgress" }
}.onFailure {
logger.fInfo { "update user status progress failed: ${it.stackTraceToString()}" }
Expand Down
11 changes: 7 additions & 4 deletions app/src/main/kotlin/dev/aaa1115910/bv/screen/VideoInfoScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ import dev.aaa1115910.bv.util.formatPubTimeString
import dev.aaa1115910.bv.util.launchPlayerActivity
import dev.aaa1115910.bv.util.requestFocus
import dev.aaa1115910.bv.util.swapList
import dev.aaa1115910.bv.util.swapListWithMainContext
import dev.aaa1115910.bv.util.toast
import dev.aaa1115910.bv.viewmodel.video.VideoDetailViewModel
import dev.aaa1115910.bv.viewmodel.video.VideoInfoState
Expand Down Expand Up @@ -194,8 +195,10 @@ fun VideoInfoScreen(
preferApiType = Prefs.apiType
)
logger.fInfo { "Following user result: $success" }
showFollowButton = success != null
isFollowing = success ?: false
withContext(Dispatchers.Main) {
showFollowButton = success != null
isFollowing = success == true
}
}
}

Expand Down Expand Up @@ -234,11 +237,11 @@ fun VideoInfoScreen(
rid = avid,
preferApiType = Prefs.apiType
)
favoriteFolderMetadataList.swapList(favoriteFolderMetadataListResult)
favoriteFolderMetadataList.swapListWithMainContext(favoriteFolderMetadataListResult)

val videoInFavoriteFolderIdsResult = favoriteFolderMetadataListResult
.filter { it.videoInThisFav }
videoInFavoriteFolderIds.swapList(videoInFavoriteFolderIdsResult.map { it.id })
videoInFavoriteFolderIds.swapListWithMainContext(videoInFavoriteFolderIdsResult.map { it.id })

logger.fDebug { "Update favoriteFolders: ${favoriteFolderMetadataList.map { it.title }}" }
logger.fDebug { "Update videoInFavoriteFolderIds: ${videoInFavoriteFolderIdsResult.map { it.title }}" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,15 @@ fun VideoPlayerV3Screen(

val updateSeek: () -> Unit = {
currentPosition = videoPlayer.currentPosition.coerceAtLeast(0L)
infoData = VideoPlayerInfoData(
val videoPlayerInfoData = VideoPlayerInfoData(
totalDuration = videoPlayer.duration.coerceAtLeast(0L),
currentTime = videoPlayer.currentPosition.coerceAtLeast(0L),
bufferedPercentage = videoPlayer.bufferedPercentage,
resolutionWidth = videoPlayer.videoWidth,
resolutionHeight = videoPlayer.videoHeight,
codec = ""//videoPlayer.videoFormat?.sampleMimeType ?: "null"
)
infoData = videoPlayerInfoData
debugInfo = videoPlayer.debugInfo
}

Expand Down Expand Up @@ -316,10 +317,11 @@ fun VideoPlayerV3Screen(
var updateSeekTimer: Timer? = null
var resetTimer: ((Long) -> Unit)? = null

val updateMask: () -> Unit = {
currentDanmakuMaskFrame = playerViewModel.danmakuMasks.firstOrNull {
val updateMask: suspend () -> Unit = {
val danmakuMasks = playerViewModel.danmakuMasks.firstOrNull {
currentPosition in it.range
}?.frames?.firstOrNull { currentPosition in it.range }
withContext(Dispatchers.Main) { currentDanmakuMaskFrame = danmakuMasks }

if (currentDanmakuMaskFrame != null) {
resetTimer?.invoke(
Expand All @@ -331,7 +333,7 @@ fun VideoPlayerV3Screen(
}

val timerTask: () -> Unit = {
scope.launch {
scope.launch(Dispatchers.IO) {
if (playerViewModel.danmakuMasks.isNotEmpty()) {
if (currentDanmakuMaskFrame == null) {
//当前无蒙版
Expand All @@ -353,7 +355,7 @@ fun VideoPlayerV3Screen(
}
} else {
//定期检查是否有蒙版
currentDanmakuMaskFrame = null
withContext(Dispatchers.Main) { currentDanmakuMaskFrame = null }
resetTimer?.invoke(2000)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import dev.aaa1115910.bv.component.videocard.SeasonCard
import dev.aaa1115910.bv.entity.carddata.SeasonCardData
import dev.aaa1115910.bv.util.ImageSize
import dev.aaa1115910.bv.util.Prefs
import dev.aaa1115910.bv.util.addAllWithMainContext
import dev.aaa1115910.bv.util.fInfo
import dev.aaa1115910.bv.util.requestFocus
import dev.aaa1115910.bv.util.resizedImageUrl
Expand Down Expand Up @@ -80,14 +81,14 @@ fun AnimeTimelineScreen(
val timelines = remember { mutableStateListOf<Timeline>() }

LaunchedEffect(Unit) {
scope.launch(Dispatchers.Default) {
scope.launch(Dispatchers.IO) {
runCatching {
timelines.addAll(
timelines.addAllWithMainContext {
seasonRepository.getTimeline(
filter = TimelineFilter.Anime,
preferApiType = Prefs.apiType
)
)
}
runCatching {
delay(200)
logger.info { "scroll to item today" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -413,11 +413,12 @@ fun UserAuthDataDialog(
) {
var qrImage by remember { mutableStateOf(ImageBitmap(1, 1, ImageBitmapConfig.Argb8888)) }

val createQr: () -> Unit = {
val createQr: suspend () -> Unit = {
val output = ByteArrayOutputStream()
QRCode(userDB.auth).render().writeImage(output)
val input = ByteArrayInputStream(output.toByteArray())
qrImage = BitmapFactory.decodeStream(input).asImageBitmap()
val image = BitmapFactory.decodeStream(input).asImageBitmap()
withContext(Dispatchers.Main) { qrImage = image }
}

LaunchedEffect(show) {
Expand Down
25 changes: 21 additions & 4 deletions app/src/main/kotlin/dev/aaa1115910/bv/util/Extends.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,40 @@ fun <T> SnapshotStateList<T>.swapList(newList: List<T>) {
addAll(newList)
}

suspend fun <T> SnapshotStateList<T>.swapList(
suspend fun <T> SnapshotStateList<T>.swapListWithMainContext(newList: List<T>) =
withContext(Dispatchers.Main) { this@swapListWithMainContext.swapList(newList) }

suspend fun <T> SnapshotStateList<T>.swapListWithMainContext(
newList: List<T>,
delay: Long,
afterSwap: () -> Unit
) {
withContext(Dispatchers.Main) {
this@swapList.swapList(newList)
}
this@swapListWithMainContext.swapListWithMainContext(newList)
delay(delay)
afterSwap()
}

suspend fun <T> SnapshotStateList<T>.addAllWithMainContext(newList: List<T>) =
withContext(Dispatchers.Main) { addAll(newList) }

suspend fun <T> SnapshotStateList<T>.addAllWithMainContext(newListBlock: suspend () -> List<T>) {
val newList = newListBlock()
withContext(Dispatchers.Main) { addAll(newList) }
}


suspend fun <T> SnapshotStateList<T>.addWithMainContext(item: T) =
withContext(Dispatchers.Main) { add(item) }


fun <K, V> SnapshotStateMap<K, V>.swapMap(newMap: Map<K, V>) {
clear()
putAll(newMap)
}

suspend fun <K, V> SnapshotStateMap<K, V>.swapMapWithMainContext(newMap: Map<K, V>) =
withContext(Dispatchers.Main) { this@swapMapWithMainContext.swapMap(newMap) }

fun <K, V> SnapshotStateMap<K, V>.swapMap(newMap: Map<K, V>, afterSwap: () -> Unit) {
this.swapMap(newMap)
afterSwap()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.aaa1115910.biliapi.http.BiliHttpApi
import dev.aaa1115910.bv.entity.carddata.VideoCardData
import dev.aaa1115910.bv.util.addWithMainContext
import dev.aaa1115910.bv.util.fInfo
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -53,7 +54,7 @@ class TagViewModel : ViewModel() {
val videoList = response.data
if (videoList.isEmpty()) noMore = true
videoList.forEach { tagVideoItem ->
topVideos.add(
topVideos.addWithMainContext(
VideoCardData(
avid = tagVideoItem.aid,
title = tagVideoItem.title,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ class UserViewModel(
userRepository.reloadAvatar()

runCatching {
responseData =
BiliHttpApi.getUserSelfInfo(sessData = Prefs.sessData).getResponseData()
val data = BiliHttpApi.getUserSelfInfo(sessData = Prefs.sessData).getResponseData()
withContext(Dispatchers.Main) { responseData = data }
logger.fInfo { "Update user info success" }
shouldUpdateInfo = false
userRepository.username = responseData!!.name
Expand Down
Loading

0 comments on commit 47aff9c

Please sign in to comment.