Coroutines not working in jetpack Compose

Viewed 34

I use the following way to get network data.

I start a network request in a coroutine but it doesn't work, the pagination load is not called.

But if I call the network request through the init method in the ViewModel I can get the data successfully.


@Composable
fun HomeView() {

    val viewModel = hiltViewModel<CountryViewModel>()

    LaunchedEffect(true) {
        viewModel.getCountryList()  // Not working
    }

    val pagingItems = viewModel.countryGroupList.collectAsLazyPagingItems()

    Scaffold {
        LazyColumn(
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 96.dp),
            verticalArrangement = Arrangement.spacedBy(32.dp),
            modifier = Modifier.fillMaxSize()) {

            items(pagingItems) { countryGroup ->
                if (countryGroup == null) return@items
                Text(text = "Hello", modifier = Modifier.height(100.dp))
            }
        }
    }
}



@HiltViewModel
class CountryViewModel @Inject constructor() : ViewModel() {

    var countryGroupList = flowOf<PagingData<CountryGroup>>()

    private val config = PagingConfig(pageSize = 26, prefetchDistance = 1, initialLoadSize = 26)

    init {
        getCountryList()    // can work
    }

    fun getCountryList() {
        countryGroupList = Pager(config) {
            CountrySource()
        }.flow.cachedIn(viewModelScope)
    }
}


I don't understand what's the difference between the two calls, why doesn't it work?

Any helpful comments and answers are greatly appreciated.

1 Answers

I solved the problem, the coroutine was used twice in the code above, which caused network data to not be fetched.

A coroutine is used here:


    fun getCountryList() {
        countryGroupList = Pager(config) {
            CountrySource()
        }.flow.cachedIn(viewModelScope)
    }


Here is another coroutine:


    LaunchedEffect(true) {
        viewModel.getCountryList()  // Not working
    }

current usage:


    val execute = rememberSaveable { mutableStateOf(true) }

    if (execute.value) {
        viewModel.getCountryList()
        execute.value = false
    }

Related