Flow Debounce for several types

653 views Asked by At

I have a screen with several switchcompats like on photo. And I want to collect only last input of each of them to send it to server. I use SharedFlow. Now I take last state by debounce but it returns only one for all the toggles. How can I use debounce or other function on Flow so as to collect last state of each of the toggles? I have a unique field in Toggle class to group by. enter image description here

1

There are 1 answers

0
Sovathna Hong On

You can create a data class to hold all the state of the switches. And update the state this data class by the switch's id.

data class SwitchesState(
    val switch1:Boolean = false,
    val switch2:Boolean = false,
    val switch3:Boolean = false,
    val switch4:Boolean = false,
    val switch5:Boolean = false
)

class SwitchesViewModel : ViewModel {

    private val _switchesFlow = MutableStateFlow(SwitchesState());
    val switchesFlow:Flow get() = _switchesFlow;

    fun updateSwitch(id:Int, state:Boolean) {
       _switchesFlow.value = when(id) {
          R.id.switch1 -> _switchesFlow.value.copy(swith1 = state)
          R.id.switch2 -> _switchesFlow.value.copy(swith2 = state)
          R.id.switch3 -> _switchesFlow.value.copy(swith3 = state)
          R.id.switch4 -> _switchesFlow.value.copy(swith4 = state)
          else -> _switchesFlow.value.copy(swith5 = state)
        }
    }

}

class SwitchesActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        
        lifecycleScope.launch {
            viewModel.switchesFlow.debounce(500).collect {
                // Do something
            }
        }
        
    }

}