'Kotlin flow - emitting value of combined 2 flows only when second flow emits a value

I want to combine two flows in that way: the combined flow emits value only when both flows emitted a value and only in moment when second flow emitted its value. When it occurs, next value is emitted again when both flows emitted new values. My pretty drawing for better understanding the expected result: First preview image

But it may appear situation like that:

Preview image 2



Solution 1:[1]

I think zip function is what you need:

flow1.zip(flow2) { result1, result2 ->
    // ... use results
}.launchIn(viewModelScope)

zip fires when each pair of value is emitted. Here is a good article about Flow operators.

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 BigSt