gaohomway
gaohomway

Reputation: 4070

Jetpack Compose ViewModel Updae Flow

I use Paging in ViewMode, and Paging returns Flow


class WindViewModel : BaseViewModel() {

    lateinit var windList : Flow<PagingData<Wind>>

    fun getWindList(path: String) {
        windList = Pager(PagingConfig(pageSize = 20)) {
            WindSource(path, user.id)
        }.flow.cachedIn(viewModelScope)
    }

    fun like(wind: Wind) {

    }

}

If I need to update Flow in the like method, how do I update it?

Upvotes: 0

Views: 101

Answers (1)

susosaurus
susosaurus

Reputation: 535

You could try using a StateFlow for windList because it lets you directly update the value of the flow with the .value property without needing to use a coroutine scope:

private val _windList: MutableStateFlow(Wind())
val windList: StateFlow<Wind> = _windList

and then update your flow in fun like(wind: Wind) accordingly:

fun like(wind: Wind) {
  _windList.value = windList.value.copy(##update changed properties here##)
}

Upvotes: 1

Related Questions