When I collect a flow I run into the problem that ...
# flow
t
When I collect a flow I run into the problem that although the value gets changed nothing happens
Copy code
val monitorDongleEuiJob = settings.dongleEui.takeWhile { dongleEui ->
        dongleEui.isNotEmpty()
    }.onEach { dongleEui ->
        // do something, but nothing happens
    }.catch {
        print(it.message)
    }.launchIn(coroutineScope)
When I change the code to this, it always works, but I don’t undestand why
Copy code
val monitorDongleEuiJob = settings.dongleEui.onEach { dongleEui ->
    if (dongleEui.isEmpty()) {
        return@onEach
    }
    // do something
}.catch {
    print(it.message)
}.launchIn(coroutineScope)
Shouldn’t it basically be the same? Or am I misunderstanding
takeWhile
? Maybe does it stop collection when the condition has been met?
s
The two code examples aren't equivalent.
return@onEach
won't terminate the flow, it's just a no-op.
t
@Sam So
takeWhile
terminates it? Then I have found my misunderstanding.
s
Yes,
takeWhile
is designed to end the flow once its value changes from
true
to
false
. Maybe you're looking for
filter
instead?
t
Ah, now I got it. Thanks a log @Sam Changed it to
Copy code
val monitorDongleEuiJob = settings.dongleEui
    .filter { it.isNotEmpty() }
    .onEach { dongleEui ->
...
I think this is what I actually need.
👍 1
🐕 2
Many thanks @Sam!