gson 我怎样才能使Http请求再次在翻新从api获得更新的数据

t5fffqht  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(164)

我想更新我从api获得的数据,以便在我的lazy列中显示它,我正在尝试添加向下滑动刷新功能。
我正在从视图模型中获取数据

@HiltViewModel
class MatchesViewModel @Inject constructor(
    private val matchRepository: MatchRepository
): ViewModel()  {

    val response: MutableState<ApiState> = mutableStateOf(ApiState.Empty)

    init {
        getAllMatches()
    }

    private fun getAllMatches() = viewModelScope.launch {

        cricketRepository.getAllMatches().onStart {

            response.value = ApiState.Loading
        } .catch {

            response.value = ApiState.Failure(it)
        }.collect {

            response.value  = ApiState.Success(it) }
}
}

然后,我创建了一个新的Kotlin文件,在该文件中,我检查是否正在获取数据并将其传递到我的lazy列中

@Composable
fun MainScreen(viewModel: MatchesViewModel = hiltViewModel()){

    when (val result = viewModel.response.value){

        is ApiState.Success -> {
            HomeScreen(matches = result.data.data)
        }

        is ApiState.Loading -> {

        }

        is ApiState.Empty -> {

        }

        is ApiState.Failure -> {

        }
    }
}

我想知道如何才能再次请求以获取更新的数据
经过一些谷歌搜索,我发现你可以用okhttp拦截器重试api调用,但找不到任何文档或教程来用拦截器重试调用

sr4lhrrt

sr4lhrrt1#

您可以尝试使用伴奏者相关性滑动以刷新

implementation "com.google.accompanist:accompanist-swiperefresh:0.26.5-rc"

实现方式是这样的

val swipeRefreshState = rememberSwipeRefreshState(false)
SwipeRefresh(
        state = swipeRefreshState,
        onRefresh = {
            swipeRefreshState.isRefreshing = false
            viewModel.<FUNCTION TO LOAD YOUR DATA>
        },
        indicator = { swipeRefreshState, trigger ->
            SwipeRefreshIndicator(
                // Pass the SwipeRefreshState + trigger through
                state = swipeRefreshState,
                refreshTriggerDistance = trigger,
                // Enable the scale animation
                scale = true,
                // Change the color and shape
                backgroundColor = <UPDATE CIRLE COLOR>,
                contentColor = <RELOADING ICON COLOR>,
                shape = RoundedCornerShape(50),
            )
        }
    ) {
        <CONTENT OF YOUR SCREEN>
      }

相关问题