簡體   English   中英

jetpack compose 中未顯示流量數據

[英]Flow data is not showing in jetpack compose

我正在嘗試從服務器獲取數據並緩存到數據庫中,並將新獲取的列表返回給用戶。 我正在獲取響應表單服務器並將其保存到本地數據庫,但是當我嘗試從可組合的 function 觀察它時,它顯示列表為空。

當我嘗試在 myViewModel class 中調試和收集流數據時,它顯示但未顯示是可組合的 function。

@Dao
interface CategoryDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(categories: List<Category>)

    @Query("SELECT * FROM categories ORDER BY name")
    fun read(): Flow<List<Category>>

    @Query("DELETE FROM categories")
    suspend fun clearAll()
}

存儲庫 class:

    suspend fun getCategories(): Flow<List<Category>> {
        val categories = RetrofitModule.getCategories().categories
        dao.insert(categories)
        return dao.read()
    }

我的視圖模型

    fun categoriesList(): Flow<List<Category>> {
        var list: Flow<List<Category>> = MutableStateFlow(emptyList())
        viewModelScope.launch {
            list = repository.getCategories().flowOn(Dispatchers.IO)
        }
        return list
    }

觀察自:

@Composable
fun StoreScreen(navController: NavController, viewModel: CategoryViewModel) {
    val list = viewModel.categoriesList().collectAsState(emptyList())
    Log.d("appDebug", list.value.toString()) // Showing always emptyList []
}

目前的回應:

2021-05-15 16:08:56.017 5125-5125/com.demo.app D/appDebug: []

您永遠不會更新已在Composable function 中收集為 state 的MutableStateFlowvalue

此外,您將Flow類型 object 分配給MutableStateFlow變量。

我們可以使用以下方法更新組合中collected的流的值:-

mutableFlow.value = newValue

我們需要將列表的類型更改為MutableStateFlow<List<Category>>而不是Flow<List<Category>>

嘗試這個:-

 var list: MutableStateFlow<List<Category>> = MutableStateFlow(emptyList()) // changed the type of list to mutableStateFlow
 viewModelScope.launch {
    repository.getCategories().flowOn(Dispatchers.IO).collect { it ->
         list.value = it
    }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM