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
相关产品推荐
相关产品推荐

