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

zak.taccardi

05/17/2020, 6:21 PM
What would be the idiomatic way to subscribe to
flowB
when
val flowA: Flow<Boolean>
emits
true
, and unsubscribe from
flowB
when
flowA
emits
false
?
Copy code
flowA.distinctUntilChanged()
.flatMapLatest { shouldSubscribe: Boolean ->
    if (shouldSubscribe) {
        flowB
    } else {
        emptyFlow()
    }
}
.launchIn(this)
maybe?
o

octylFractal

05/17/2020, 6:37 PM
that seems to work pretty well
👍 1
t

Tash

05/17/2020, 6:41 PM
yup
flatMapLatest
looks like the way to go
👍 1
g

gildor

05/18/2020, 8:17 AM
offtopic: I’m still confused with name flatMapLatest, switchMap makes more sense for me. I almost start arguing that
switchMap
is the way to implement this, until I realised that flatMapLatest is the same Of course I’m biased, too many years of RxJava usage, but still “switch” which actually helps me understand what this function does
t

Tash

05/18/2020, 8:37 AM
@gildor yeah. saw that there was this discussion re: the name https://github.com/Kotlin/kotlinx.coroutines/issues/1335 Taken from there:
This nomenclature produces the following distinctly named variants of 
flatMap
 operator with different merging strategies:
• `flatMapConcat`/`flattenConcat` -- concatenates all flows. • `flatMapLatest`/`flattenLatest` -- cancels ongoing flow as soon as the new one appears. • `flatMapMerge`/`flattenMerge` -- concurrently run flows and merge their results. Got more context on the name after reading that.
g

gildor

05/18/2020, 8:45 AM
Yes, I’m aware about this renaming, just still not convinced
Now instead I’m confused about all 3 of them 🙈
🙈 1
3 Views