@@ -23,6 +23,8 @@ import dev.icerock.moko.resources.compose.stringResource
2323import kotlinx.coroutines.Dispatchers
2424import kotlinx.coroutines.GlobalScope
2525import kotlinx.coroutines.delay
26+ import kotlinx.coroutines.flow.collectLatest
27+ import kotlinx.coroutines.isActive
2628import kotlinx.coroutines.launch
2729import project.pipepipe.app.MR
2830import project.pipepipe.app.SharedContext.navController
@@ -46,20 +48,39 @@ fun DownloadScreen(
4648
4749 var showCancelAllDialog by remember { mutableStateOf(false ) }
4850
49- // Auto-refresh downloads periodically
50- LaunchedEffect (Unit ) {
51- while (true ) {
52- viewModel.refreshDownloads()
53- delay(1000 ) // Refresh every second
54- }
55- }
5651
5752 var selectedTab by remember { mutableStateOf(0 ) }
5853 val tabs = listOf (
5954 " Downloading" to DownloadStatus .DOWNLOADING ,
6055 " Completed" to DownloadStatus .COMPLETED ,
6156 " Failed" to DownloadStatus .FAILED
6257 )
58+ // 监听 selectedTab 的变化
59+ LaunchedEffect (Unit ) {
60+ snapshotFlow { selectedTab }
61+ .collectLatest { tab ->
62+ // collectLatest 特性:当 selectedTab 变化时,取消上一个 block 的协程
63+ if (tab == 0 ) {
64+ while (isActive) { // 使用 isActive 检查协程状态
65+ val activeDownloads = viewModel.getActiveDownloads()
66+
67+ // 只有当真的有东西在下载时,才频繁刷新
68+ if (activeDownloads.isNotEmpty()) {
69+ viewModel.refreshDownloads()
70+ delay(1000 ) // 1秒刷新一次
71+ } else {
72+ // 关键修改:如果为空,不要 break!而是进入"低功耗"轮询
73+ // 或者更好的方式是:在这里挂起,直到 ViewModel 发送"有新任务"的事件
74+ delay(3000 ) // 列表为空时,3秒检查一次,节省性能
75+ }
76+ }
77+ } else {
78+ // 刚切到其他 Tab 时刷一次即可
79+ viewModel.refreshDownloads()
80+ }
81+ }
82+ }
83+
6384
6485 Column (modifier = Modifier .fillMaxSize()) {
6586 if (! useAsTab) {
0 commit comments