问题描述
我有一个 MutableStateFlow 和一个 Flow 变量。如何将 selectedCollection 的初始值设置为 collections 流列表的第一项?
视图模型
@Hiltviewmodel
class Homeviewmodel @Inject constructor(
private val collectionRepo: CollectionRepositoryInterface
) : viewmodel(){
var collections = collectionRepo.getCollections().asLiveData()
val selectedCollection = MutableStateFlow(//** Initial Value **//)
}
存储库界面
interface CollectionRepositoryInterface {
fun getCollections() : Flow<List<Collection>>
}
片段
viewmodel.collections.observe(viewLifecycleOwner){
collectionAdapter.submitList(it)
}
解决方法
也许你可以试试 stateIn
fun <T> Flow<T>.stateIn(
scope: CoroutineScope,started: SharingStarted,initialValue: T
): StateFlow<T> (source)
将流转换为状态流