0

morning all, let's say I have this code

    internal val canAllowProcess: StateFlow<Boolean> = combine(
        _isLoading, _isEligible
    ) { arg1, arg2 -> 
        // do something here
    }.stateIn(
        scope = viewModelScope, // how long this variable should survive
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = false
    )

My question is, will this canAllowProcess emit data only if _isLoading and _isEligible (they are both StateFlow) are both emitting new data? (I thought as long as one flow emit the new data, then canAllowProcess will also be triggered)

Thanks in advance!

Ryan Chen
  • 170
  • 1
  • 7

1 Answers1

0

If they're StateFlows themselves, they will have initial values, and those values will be taken by combine immediately. Following that, combine will be triggered every time one of the flows emits a new value.

So, for example:

  1. initialValues: isLoading = false, isEligible = false -> combine is triggered with (false, false)
  2. isLoading changes to true -> combine is triggered with (true, false)
  3. isEligible changes to true -> combine is triggered with (true, true)
  4. isLoading changes to false -> combine is triggered with (false, true)

The flow method that works in pairs is zip. With zip, this same scenario would look like this:

  1. initialValues: isLoading = false, isEligible = false -> zip is triggered with (false, false)
  2. isLoading changes to true -> zip not triggered
  3. isEligible changes to true -> zip is triggered with (true, true)
  4. isLoading changes to false -> zip not triggered
Serge
  • 359
  • 2
  • 13