Given a `val isLoggedIn: Flow<Boolean>` that...
# coroutines
z
Given a
val isLoggedIn: Flow<Boolean>
that can emit
true
or
false
in any order and multiple times each - what would be the best way to observe when it switches from
true
to
false
? I would like to run a function when the user logs out - meaning the
Flow<Boolean>
emits
true
then
false
?
Copy code
val isLoggedIn: Flow<Boolean>

isLoggedIn
  // <-- what operators do I need here?
  .onEach { 
    onLogout()
  }
  .launchIn(scope)
t
Could you use
distinct
, and then just check if your value is
false
in you
onEach
block?
👍 2
z
Copy code
.distinctUntilChanged()
.filter { it }
👍 2
z
oh that was easy
lol
wait I think I want the inverse
t
Yeah,
filterNot { it }
👍 1
z
but if the first value is
false
- won’t it emit and incorrectly call
onLogout()
I specifically want to run a function only when the stream switches from
true
to
false
so a single
flow { emit(false) }
should not trigger the
onLogout()
t
I'm not sure what this would look like. Some kind of buffer? Maybe have a look at what distinct does under the hood?
z
I think the following may work
Copy code
.distinctUntilChanged()
.drop(1)
.filterNot { it }
☝️ 1
so
false
would not pass through the filter, but
false, true, false
would and
true, false
would as well
t
Hah that was also easy
👍 1
s
You could also use the
areEquivalent(old,new)
parameter of distinctUntilChanged to only match old = true and new = false
👏 4