You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android ViewModel中CountDownTimer的onFinish重复触发问题排查

ViewModel倒计时器功能异常排查及疑问

我尝试在ViewModel中实现一个10秒倒计时器,到期后返回上一视图,但出现多个异常:

  • onFinish方法会触发两次返回操作
  • 调用counter?.cancel()无法取消计时器
  • ViewModel的onCleared方法似乎从未执行
  • 同时疑惑CountDownTimer是否可以在ViewModel中使用

相关ViewModel代码如下:

class PairingScreenViewModel(
    private val routing: NavController,
) : ViewModel() {
    var content = mutableStateOf(10)
    var counter: CountDownTimer? = null

    init {
        viewModelScope.launch {
            delay(1000L)
            counter = object : CountDownTimer(9000L, 1000L) {
                override fun onTick(millisUntilFinished: Long) {
                    content.value = content.value.dec()
                }

                override fun onFinish() {
                    routing.popBackStack() // 会执行两次返回,原因不明?
                }
            }.start()
        }
    }

    override fun onCleared() {
        super.onCleared() // 似乎从未执行
        counter?.cancel()
    }

    fun onButtonClicked() = viewModelScope.launch {
        counter?.cancel() // 无法取消计时器
        routing.navigate("next-route")
    }
}

编辑补充:我怀疑问题出在NavHostController的使用上,这是我首次使用androidx.navigation:navigation-compose,MainActivity相关代码如下:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val routing = rememberNavController()
            val heading = "MyApplication"
            AndroidNavigationDemoTheme {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = { Text(heading, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth()) }
                            )
                        },
                        content = {
                            Router(routing)
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun Router(routing: NavHostController) {
    NavHost(
        navController = routing,
        startDestination = "welcome"
    ) {
        composable("welcome") {
            WelcomeScreen(routing)
        }
        composable("hisense") {
            HisenseScreen(HisenseScreenViewModel(routing))
        }
        composable("pairing") {
            PairingScreen(PairingScreenViewModel(routing))
        }
        // ...
    }
}

内容的提问来源于stack exchange,提问作者0lan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:36:29