在即时比分应用程序中,如何在不重新打开应用程序的情况下更新比赛结果? 这是我的 ViewModel 代码示例,如果有人可以提供帮助。
@HiltViewModel
class LiveMatchesViewModel @Inject constructor(private val liveMatchesRepository: LiveMatchesRepository): ViewModel() {
private var _liveMatchesState = MutableStateFlow<MatchState>(MatchState.Empty)
val liveMatchesState: StateFlow<MatchState> = _liveMatchesState
init {
getAllLiveMatches()
}
private fun getAllLiveMatches() {
_liveMatchesState.value = MatchState.Loading
viewModelScope.launch(Dispatchers.IO) {
try {
val liveMatchesResponse = liveMatchesRepository.getLiveMatches()
_liveMatchesState.value = MatchState.Success(liveMatchesResponse)
}
catch (exception: HttpException) {
_liveMatchesState.value = MatchState.Error("Something went wrong")
}
catch (exception: IOException) {
_liveMatchesState.value = MatchState.Error("No internet connection")
}
}
}
}
LaunchedEffect
可组合项来实现此目的:
LaunchedEffect(Unit) {
while (true) {
liveMatchesViewModel.getAllLiveMatches()
delay(20000) // wait for 20 seconds
}
}
这将每 20 秒重新执行一次
getAllLiveMatches
函数。您需要将 getAllLiveMatches
设为公共函数才能实现此功能。