'How to set block scope variables in flow

The code below is modified for those who will read the question:

My code looks something like this:

private suspend fun decrementCount(): Boolean {
 ...
var isGetCountSuccess: Boolean
val isDecrementCountSuccess = decrementTapCountUseCase(_tapCounter.value)

  functionThatReturnsFlow().onEach {
    if (it in 0..1000) {
       _tapCounter.value = it  
    } else { 
       isGetCountSuccess = false // this doesn't work. how do I make this work?
    }
  }

  return isGetCountSuccess && isDecrementCountSuccess
}

the function that is used to return the Flow looks like this:

fun functionThatReturnsFlow(): Flow<Int> = flow {
  try {
    preferencesManager.getTapCount().collect { emit(it) }
  } catch (e: Exception) {
    Timber.e("Failed to get count from preferences --> $e")
    emit(-1)
  }
}

Essentially what happens is that the decrementTapCountUseCase updates the tapCounter stored in preferences. and then I get the new value from preferences using the functionThatReturnsFlow.

Basically, after about 3 hours of trying to refactor this code, I ended up with what I got above. The logic of the code goes as follows:

  1. decrement counter
  2. fetch updated count
  3. if both of these were successful, play an animation

So far I have this:

  1. the decrement counter function returns a boolean signaling whether it was successful or not
  2. the fetch new updated count function returns -1 upon failure. The only problem is, I do not know how to set the isGetCountSuccess variable. Setting it in the onEach function DOES NOT WORK. Is there a better way to do what I'm trying to do? I cannot use a .catch since the flow technically never fails at any point. I just need to set the isCountSuccess Boolean based on the flow's value


Sources

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

Source: Stack Overflow

Solution Source