Home > Back-end >  How to emit/collect with Kotlin flow while a condition is true
How to emit/collect with Kotlin flow while a condition is true

Time:05-09

I am learning about Kotlin Flows and am wondering how to deal with following scenario in Android:

I have some event coming from my Fragment that will trigger a boolean value, which can be observed through a StateFlow. (The value is true while the user is pressing on the screen).

While the user is pressing on the screen, there can be some input from the camera feed to an OCR processing pipeline. For each processing result, there should be a sound played, and also I want to collect the results of this processing pipelines from the time period, giving back a final result when the user lets go of the press.

So approximately, the event flow is: user does a long press on the screen and holds the camera onto multiple things -> he gets some results -> each result triggers some further UI event -> user lets go -> there is a final UI feedback event when all results are evaluated together

Is there any nice way to do this with Kotlin Flows?

CodePudding user response:

I can suggest the following approach:

When user presses the screen val state = StateFlow<Boolean>(...) changes to true and some function is triggered, which returns a Flow. The implementation of this function can be the following:

fun triggerWhenUserPresses() = flow {
      var evaluatedResults = ...
      while(state.value) {
          // process and emit results
          evaluatedResults = ... // evaluate result
      }
      emit(/*final UI feedback, evaluatedResults*/)
}

When user stops pressing the screen the state changes to false and the while loop in triggerWhenUserPresses function finishes, and after the loop you can emit the "final UI feedback" with evaluated results.

CodePudding user response:

You can use callbackFlow because you want to emit multiple events and filter the results from the flow using takeWhile { } operator or filter { }

  • Related