'How to deal with viewholder and flow in recyclerview?

I would like to use my variable flow to save integer and keep him. Then every viewholder in recyclerview observe flow and react if it is clicked. For example:

I have cardView when I click on that I use method

statusButtons.toggleVisibility(!statusButtons.isVisible)

.. then my element expose like in the swipe mode, if I click on another element, previous element should (swipe back) or just toggleVisisbility to isNotVisible in my case.

Now, if I click on my element everytime I trigger only this one element so I can't hide others and make actions on this.

For now I started like that:

    val _stateFlow = MutableStateFlow(-1)
    val stateFlow = _stateFlow.asStateFlow()


cardView.onClickListener {

_stateFlow.value = absoluteAdapterPosition
}


Solution 1:[1]

Hej Chrisu,

the stateFlow should be part of your Adapter and when you build a new ViewHolder you inject the variable into the ViewHolder. With this the stateFlow is only created once and all holders can observe it.

Something like this:

Adapter{
    val stateFlow = MutableStateFlow(-1)

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder = 
    ViewHolder(stateFlow)
}


ViewHolder(val stateFlow: MutableStateFlow){

    init{
      cardView.onClickListener {
        _stateFlow.value = absoluteAdapterPosition
      }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Knauf