你忘了调用 Flow<PagingData<*>>.cachedIn(coroutineScope) 了吗?

Did you forget to call Flow<PagingData<*>>.cachedIn(coroutineScope)?

如何修复 IllegalStateException:尝试从 pageEventFlow 收集两次,这是非法操作。

您是否忘记调用 Flow>.cachedIn(coroutineScope)?

代码:

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.kharismarizqii.movieapp.data.MovieRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class MovieViewModel @Inject constructor(
    private val repository: MovieRepository,
    state: SavedStateHandle) : ViewModel(){

    companion object{
        private const val CURRENT_QUERY = "current_query"
        private const val EMPTY_QUERY = ""
    }

    private val currentQuery = state.getLiveData(CURRENT_QUERY, EMPTY_QUERY)
    val movies = currentQuery.switchMap { query ->
        if (query.isNotEmpty()){
            repository.getSearchMovies(query)
        }else{
            repository.getNowPlayingMovies().cachedIn(viewModelScope)
        }
    }

    fun searchMovies(query: String){
        currentQuery.value = query
    }
}

崩溃:

  java.lang.IllegalStateException: Attempt to collect twice from pageEventFlow, which is an illegal operation. Did you forget to call Flow<PagingData<*>>.cachedIn(coroutineScope)?
  

您应该将 getSearchMovies 的数据缓存到

    private val currentQuery = state.getLiveData(CURRENT_QUERY, EMPTY_QUERY)
    val movies = currentQuery.switchMap { query ->
        if (query.isNotEmpty()){
            repository.getSearchMovies(query).cachedIn(viewModelScope)
        }else{
            repository.getNowPlayingMovies().cachedIn(viewModelScope)
        }
    }