How to correctly use pull to refresh in Jetpack Compose?

1.3k Views Asked by At

I'm trying to implement pull to refresh in my screen. But I have a problem, when updating I need to execute two requests in parallel, but as you can see from my code, I do not wait for the result from two requests, I update the state as data arrives:

fun refresh() {

 viewModelScope.launch(genericErrorHandler) {
            launch {             
             
                    val data = interactor.firstRequest()
                    _state.update {
                        it.copy(
                            firstData = data,
                          
                        )
                    }               
            }

            launc {                 
                _state.update {
                    it.copy(secondData = interactor.fetchSecondData())
                }
            }
        }
}

But I need to add isRefreshing flag to my ViewModel to track when the refresh action has started and finished.

val pullRefreshState = rememberPullRefreshState(
        state.isRefreshing,
        onRefresh,
    )

And how to determine when to set the value for the isRefreshing flag to false ? Please, help me.

1

There are 1 best solutions below

0
VanSuTuyDuyen On

As my understanding, you don't want user to do accident pull request when the viewmodel is loading. So first you can create a

enum class ScreenState { 
    LOADING, READY 
}

and let the ViewModel keep the StateFlow<ScreenState>, with this your UI will acknowledge when it is ready for pull request.

Next, besides logic part, on the UI part you can stop user by passing enabled of

Modifier.pullRefresh(state: PullRefreshState, enabled: Boolean)