https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
l

Leo Delon

05/02/2023, 4:09 PM
Hey yall. I'm having a combining flow issue. I have two flows of different types that depend on an id. I need to combine them in such a way that if flow B receives an emission, the entire flow needs to emit again the current state. I tried
combine
combineTransform
zip
and
merge
with no success. The first emission occurs correctly. but once only B emits it doesn't get propagated downstream. Any ideas on what I could try?
private val _state = MutableStateFlow<State>(State.Loading)

fun loadData(collectionId: String) {
    viewModelScope.launch {
        val collectionFlow = repository.getCollection(collectionId)
        val itemsFlow = repository.getCollectionItems(collectionId)
        
        combine(collectionFlow, itemsFlow, ::Pair).flatMapConcat { (collection, items) ->
            val map = ...// maps the data
            modelUseCase(map) // sends to another flow
         }.collect{ model ->
            if (model.items.isEmpty()) {
                _state.value = State.Empty
            } else {
                _state.value = State.Content(model)
            }
        }
    }    
}
k

kevin.cianfarini

05/02/2023, 4:25 PM
fun flowFromId(id: String): Flow<Pair<A, B>> = combine(
  flowAFromId(id),
  flowBFromId(id),
  ::Pair,
)

fun flowAFromId(id: String): Flow<A> = flow { /* omitted */ }
fun flowBFromId(id: String): Flow<B> = flow { /* omitted */ }
Without seeing your code it’s impossible to know what’s going wrong, but the above sample should work to emit on every constituent flow emission
l

Leo Delon

05/02/2023, 4:32 PM
Will try
I tried but the emission is not being propagated 😞
@kevin.cianfarini code above
collectionFlow emits but combine doesn't receive anything
k

kevin.cianfarini

05/02/2023, 5:28 PM
To debug you should simplify the above code to see if anything is happening at all. You’ve got quite a bit of moving parts in there. I’d suggest:
val collectionFlow = repository.getCollection(collectionId)
        val itemsFlow = repository.getCollectionItems(collectionId)
        
        combine(collectionFlow, itemsFlow, ::Pair).collect { (collection, items) ->
          error("Got an item!")
        }
If that produces an error then you know the combine is working.
I am suspicious of your flatmapConcat there being the bug
I doubt that it’s combine that isn’t emitting.
l

Leo Delon

05/02/2023, 5:29 PM
I added onEach for each flow. Both are emitting fine
GPT says
The
combine
operator of Kotlin Flow waits until all flows emit at least one value before it starts emitting combined values. If any of the flows don't emit a value, the
combine
operator won't emit any value. To solve this problem, you can use the
onEach
operator to apply a side effect and ensure that each flow emits at least one value. For example:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking<Unit> {
    val flow1 = flowOf(1, 2, 3)
    val flow2 = flowOf("A", "B", "C")

    flow1
        .onEach { /* Applying a side effect */ }
        .combine(flow2.onEach { /* Applying a side effect */ }) { i, s -> "$i$s" }
        .collect { println(it) }
}
k

kevin.cianfarini

05/02/2023, 5:29 PM
Side effects have nothing to do with how flows work in combine. Do not trust that ChatGPT is correct. Consult the documentation.
l

Leo Delon

05/02/2023, 5:30 PM
I have onEach after combine
k

kevin.cianfarini

05/02/2023, 5:30 PM
If either of your flows are not emitting an item you can wrap them with something like
.onStart { emit(item) }
to ensure a flow has an item
l

Leo Delon

05/02/2023, 5:30 PM
nothing comes through
even though one of the flows emitted
k

kevin.cianfarini

05/02/2023, 5:30 PM
Both of the flows need to emit for combine to emit
l

Leo Delon

05/02/2023, 5:31 PM
the problem occurs on the second emission
k

kevin.cianfarini

05/02/2023, 5:31 PM
if only one is emitting then there’s your problem
l

Leo Delon

05/02/2023, 5:31 PM
first time they both load and all works
when one changes
the combine doesn't work
k

kevin.cianfarini

05/02/2023, 5:32 PM
You need to provide a better reproducer than what you’ve given. Give me something along the lines of the following:
val flow = flowOf(1, 2).onEach { delay(10) }
val flow2 = flowOf("a", "b", "c").onEach { delay(15) }
flow.combine(flow2) { i, s -> i.toString() + s }.collect {
    println(it) // Will print "1a 2a 2b 2c"
}
l

Leo Delon

05/02/2023, 5:32 PM
ok
fun main() {
    val flow1 = MutableSharedFlow<Int>()
    val flow2 = MutableSharedFlow<String>()

    
    GlobalScope.launch {
        launch {
           flow1.combine(flow2) { i: Int, s: String -> i.toString() + s }
                .collect {
               		println(it)
           		} 
        }
        
        delay(100)
        flow1.emit(1)
        flow2.emit("a")
        delay(100)
        flow1.emit(2)
        delay(100)
        flow2.emit("b")
        
    }
}
this works ☝️
val collectionFlow = repository.getCollection(collectionId).onEach {
    Timber.d("loadData ${it.name}")
}
val itemsFlow = repository.getCollectionItems(collectionId).onEach {
    Timber.d("loadData ${it.size}")
}

collectionFlow.combine(itemsFlow) { collection, items ->
    Timber.d("loadData ${items.size}")
    collection to items
}
this doesn't work after the first emission
even though the individual flows emit
k

kevin.cianfarini

05/02/2023, 6:03 PM
Do you collect this at all? Right now it looks like it’s not being
collected
.
val collectionFlow = repository.getCollection(collectionId).onEach {
    Timber.d("loadData ${it.name}")
}
val itemsFlow = repository.getCollectionItems(collectionId).onEach {
    Timber.d("loadData ${it.size}")
}

collectionFlow.combine(itemsFlow) { collection, items ->
    Timber.d("loadData ${items.size}")
    collection to items
}
l

Leo Delon

05/02/2023, 6:03 PM
I do collect it at the end
first collection works
k

kevin.cianfarini

05/02/2023, 6:03 PM
What does your log look like
l

Leo Delon

05/02/2023, 6:09 PM
D  loadData Newer // Flow 1 - Emission 1
D  loadData 2 // Flow 2 - Emission 1
D  loadData 2 // Combine - Emission 1
D  loadData Newest // Flow 1 - Emission 2
I'm collecting the flow inside of a function in my viewmodel
k

kevin.cianfarini

05/02/2023, 6:15 PM
Can you change your debug logs just for the sake of clarity to be:
val collectionFlow = repository.getCollection(collectionId).onEach {
    Timber.d("getCollectionFlow ${it.name}")
}
val itemsFlow = repository.getCollectionItems(collectionId).onEach {
    Timber.d("getCollectionItems ${it.size}")
}

collectionFlow.combine(itemsFlow) { collection, items ->
    Timber.d("combine ${collection.name}: ${items.size}")
    collection to items
}
and then post the logs
l

Leo Delon

05/02/2023, 6:16 PM
I'm trying returning my flow
instead of collecting
D  getCollectionFlow Newest
D  getCollectionItems 2
D  combine Newest: 2
D  getCollectionFlow Newer
kotlin=1.8.10
kotlinx.coroutines=1.6.4
k

kevin.cianfarini

05/02/2023, 6:31 PM
Hmmmmm
Try and see if the flow is completing:
collectionFlow.combine(itemsFlow, ::Pair).onCompletion { /* log completion here */ }
I have one more idea after that but let’s see that result first
That
onCompletion
function takes an optional throwable as the cause. Would be good to log that
l

Leo Delon

05/02/2023, 6:38 PM
tried
not completing. Meaning no log
Trying coroutines 1.7.0-Beta with compatibility for kotlin 1.8.10
also no change
k

kevin.cianfarini

05/02/2023, 6:51 PM
can you
.take(2).toList()
to see what happens?
Otherwise you should inline the body of
combine
to see where it’s failing:
fun <T, E, R> Flow<T>.myCombine(other: Flow<E>, tansform: (T, E) -> R): Flow<R> {
  return combineTransform(flow2) { a, b -> 
    println("Got values $a and $b")
    val value = transform(a, b)
    println("emitting $value")
    emit(value)
    println("emitted $value") 
  }
}
l

Leo Delon

05/02/2023, 6:57 PM
how could I take after the first emission (where the problem happens?
k

kevin.cianfarini

05/02/2023, 6:58 PM
Can you clarify?
l

Leo Delon

05/02/2023, 7:01 PM
I don't know how taking 2 would work to catch the issue
k

kevin.cianfarini

05/02/2023, 7:02 PM
I was curious to see if it would suspend forever or throw some sort of exception
l

Leo Delon

05/02/2023, 7:03 PM
D  getCollectionFlow yoyoyoyt
D  getCollectionItems 0
D  Got values AssetCollection(id=VX9MXud3QWUsAFwuAJlx, name=yoyoyoyt, itemCount=78, timestamp=Fri Mar 03 10:10:03 GMT+01:00 2023) and []
D  combine yoyoyoyt: 0
D  emitting (AssetCollection(id=VX9MXud3QWUsAFwuAJlx, name=yoyoyoyt, itemCount=78, timestamp=Fri Mar 03 10:10:03 GMT+01:00 2023), [])
D  getCollectionFlow yoyoyoyx
the kotlin sample works so is definitely something with my flows
k

kevin.cianfarini

05/02/2023, 7:13 PM
You should add
onCompletion
to each of your constituent flows to see if either of them are completing.
l

Leo Delon

05/02/2023, 7:15 PM
I did
none is
ok
think I found it
k

kevin.cianfarini

05/02/2023, 7:23 PM
What went wrong?
l

Leo Delon

05/02/2023, 7:25 PM
it's probably the flatmapConcat
that other flow is also combining
something wrong there could throw the whole thing off
combining without it is collecting
k

kevin.cianfarini

05/02/2023, 7:26 PM
Ah yep that'll do it
l

Leo Delon

05/02/2023, 7:38 PM
onCompletion kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled