使用Retrofit2进行API调用:如何一直进行API调用,在不重新打开应用程序的情况下更新数据

问题描述 投票:0回答:1

在即时比分应用程序中,如何在不重新打开应用程序的情况下更新比赛结果? 这是我的 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")
            }
        }
    }
}
android kotlin android-jetpack-compose retrofit2 kotlin-coroutines
1个回答
0
投票

您可以使用

LaunchedEffect
可组合项来实现此目的:

LaunchedEffect(Unit) {
    while (true) {
        liveMatchesViewModel.getAllLiveMatches()
        delay(20000)  // wait for 20 seconds
    }
}

这将每 20 秒重新执行一次

getAllLiveMatches
函数。您需要将
getAllLiveMatches
设为公共函数才能实现此功能。

© www.soinside.com 2019 - 2024. All rights reserved.