https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

zak.taccardi

07/10/2022, 6:49 PM
Given a
StateFlow<T>
instance, I want to log every emission of
T
from the source standpoint. Is this possible without duplicating logs for each subscriber?
We currently log at this point (before converting into a state flow):
Copy code
.scan { .. }
.logEachState(logger)
.stateIn(scope)
But this will log duplicate values that are not emitted to subscribers. We had a bug where
T
was not immutable and was not emitting when it’s
var
changed bc only the instance was mutated - (same instance will not be emitted twice in a row due to equality checks, even if the value changes)
if we logged at each subscriber, then we risk some real noisy logs
d

Dominaezzz

07/10/2022, 8:23 PM
If I understand correctly, you basically want to swap line 2 and 3?
z

zak.taccardi

07/10/2022, 8:38 PM
Yep, but it's a
doOnNext()
which returns a
Flow<T>
- and I want a
StateFlow<T>
d

Dominaezzz

07/10/2022, 8:43 PM
Hmm, okay I understand. I have an idea.
Copy code
.scan { .. }
.stateIn(scope)
.apply { logEachState(logger).launchIn(scope) }
Oh wait, I'm guessing you don't want to log when there are no subscribers. If that's the case my code snippet won't work.
You could add a
distinctUntilChanged()
to your snippet I guess.
I have no other trivial ideas.
s

stojan

07/11/2022, 9:25 AM
I guess you need something like this: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1652287040843249 but for
onEach
d

DALDEI

07/27/2022, 11:13 PM
Reworked - <duh> Expose your State flow like // expose as val state = flow { ...} .stateIn(scope) // Log with private loggy = state.onEach { log(it) }.launchIn(..)
12 Views