Erdem Kalyoncu
Erdem Kalyoncu

Reputation: 161

How to set MutableStateFlow initial value from Flow List

I have a MutableStateFlow and a Flow variable. How can I set the initial value of selectedCollection as the first item of the collections Flow list?

ViewModel

@HiltViewModel
class HomeViewModel @Inject constructor(
        private val collectionRepo: CollectionRepositoryInterface
) : ViewModel(){

    var collections = collectionRepo.getCollections().asLiveData()
    val selectedCollection = MutableStateFlow(//** Initial Value **//)
    
}

Repository Interface

interface CollectionRepositoryInterface {
    fun getCollections() : Flow<List<Collection>>
}

Fragment

viewModel.collections.observe(viewLifecycleOwner){
    collectionAdapter.submitList(it)
}

Upvotes: 3

Views: 5860

Answers (1)

lee
lee

Reputation: 76

Maybe you could try stateIn

fun <T> Flow<T>.stateIn(
    scope: CoroutineScope,
    started: SharingStarted,
    initialValue: T
): StateFlow<T> (source)

Convert flow to a stateFlow

Linked this: enter link description here

Upvotes: 3

Related Questions