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
hiring-french
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
t

Tim Malseed

07/16/2020, 6:29 AM
I apologise for all these dumb questions, but anyway.. Why does this work:
override fun loadData() {
        launch {
            songRepository.getSongs(SongQuery.Album(name = album.name, albumArtistName = album.albumArtist))
                .collect { songs ->
                    this@AlbumDetailPresenter.songs = songs
                    view?.setData(songs)
                }
        }
    }
But this doesn’t:
override fun loadData() {
        launch {
            songRepository.getSongs(SongQuery.Album(name = album.name, albumArtistName = album.albumArtist))
                .collect { songs ->
                    this@AlbumDetailPresenter.songs = songs
                }
            view?.setData(songs)
        }
    }
In the second case, shouldn’t 
view?.setData(songs)
 only get called after 
collect {}
 has completed?
o

octylFractal

07/16/2020, 6:31 AM
yes, I think so, not sure how it would work out coroutine-wise otherwise
t

Tim Malseed

07/16/2020, 6:32 AM
Well, it seems like it doesn’t get called at all
o

octylFractal

07/16/2020, 6:32 AM
are you sure
view
is non-null?
not sure why it would differ between the top and bottom in that case though
t

Tim Malseed

07/16/2020, 6:32 AM
Yes. But in the second case,
view?.setData(songs)
is not called (breakpoint not hit in debugger) - even if
view
was null I’d still expect the line to be hit
o

octylFractal

07/16/2020, 6:33 AM
I would verify with a logging statement, sometimes the debugger isn't perfect for Kotlin in my experience
g

gildor

07/16/2020, 6:33 AM
Probably collect never finish
o

octylFractal

07/16/2020, 6:33 AM
that is a good point
g

gildor

07/16/2020, 6:34 AM
so first works just because it receives result to collect and notify, but second never passed collect function
t

Tim Malseed

07/16/2020, 6:34 AM
I see, that makes sense
g

gildor

07/16/2020, 6:34 AM
Check that you don’t use something like StateFlow in your getSongs method, it never completes
t

Tim Malseed

07/16/2020, 6:35 AM
I am indeed using StateFlow!
Thanks
I just need to use the first option. But this is another good little lesson in Coroutines
I’m slowly getting through all the gotchas
g

gildor

07/16/2020, 6:36 AM
it’s general rule of reactive frameworks, if you have stream it’s better do not expect that it will complete, because it’s an implementation detail, it may return 0-Infinite number of elements, and can never complete
t

Tim Malseed

07/16/2020, 6:36 AM
Yeah, I’m not actually expecting it to complete - just a mistake in the braces placement - and then I forgot that it doesn’t complete
👍 1
This is great. I think I have made the same error in a few places, so remembering not to assume
collect
will complete for streams is a good lesson
g

gildor

07/16/2020, 6:39 AM
You also can use launchIn(), so you never have suspending collect, will work just as launching collection in background (exactly waht you are doing in this case by wrapping with launch), also makes it less nested:
songRepository.getSongs(...)
   .onEach { setData(it) }
   .launchIn(scope)
👍 1
t

Tim Malseed

07/16/2020, 6:40 AM
Oh yeah, that’s quite nice
So, are you saying never assume a Flow completes? Like, do you think it’s always a mistake to call
launch {
    flow.collect {

    }
    doSomething()
}
Because that requires knowledge of whether the flow will complete, which, as you say, is an implementation detail?
g

gildor

07/16/2020, 6:42 AM
not always mistake, but it means that you expect that you know contract of this flow, that it should complete at some point
t

Tim Malseed

07/16/2020, 6:44 AM
I would usually use a suspend fun rather than a flow if I expect completion. But for some things, I want to emit elements along the way to completion
g

gildor

07/16/2020, 6:44 AM
I wouldn’t call it mistake, sometimes you have a reson for this. For example recently in this Slack it was discussion about implementation of Spring Webflux API for database, which exposes select as stream of events, but not like usually you expect subsribe on data updates in table, but to make select of different rows lazy, so it completes when all rows are selected
so it’s not mistake there, but you should know contract of stream which you request
t

Tim Malseed

07/16/2020, 6:44 AM
Yeah, I see what you’re saying
Thanks
g

gildor

07/16/2020, 6:46 AM
But it may be a source of errors, especially when code changes, so you may be in situtation when code is changed but API of it is the same, it just exposes Flow
t

Tim Malseed

07/16/2020, 6:46 AM
It would be nice if you could declare whether a Flow completes or not
g

gildor

07/16/2020, 6:58 AM
But how would such type would look like?
t

Tim Malseed

07/16/2020, 6:59 AM
Well, I’m not suggesting that the Coroutines API be changed, or that I have the answer. I just mean, it might be useful for this exact scenario
o

octylFractal

07/16/2020, 6:59 AM
I suspect it would be somewhat similar to
Mono
in rx
g

gildor

07/16/2020, 6:59 AM
It’s not only problem of coroutines, it’s true for any reactive-like type
Mono is too limited, and coroutines do not need mono, we already have suspend functions
t

Tim Malseed

07/16/2020, 7:00 AM
Suspend functions aren’t the solution for this either - if you need intermediate emissions before completion
g

gildor

07/16/2020, 7:01 AM
anyFlow..first() is the same as Mono
if you need intermediate emissions before completion
What do you mean?
My point is that if you need only single value (what Mono or Single doing), just use suspend function
t

Tim Malseed

07/16/2020, 7:02 AM
Yeah, sounds like Mono is not the solution to this problem then
o

octylFractal

07/16/2020, 7:02 AM
I was suggesting a more general form of Mono, which implies a
0..N
g

gildor

07/16/2020, 7:03 AM
How Mono is the solution?
o

octylFractal

07/16/2020, 7:03 AM
it isn't, never mind me
I'm not able to communicate what I mean, clearly
g

gildor

07/16/2020, 7:04 AM
which implies a 
0..N
This is the same what Flow or rxjava Observable or Flux is and it exactly the same problem
j

julian

07/16/2020, 7:05 AM
Tests!
:yes: 1
☝️ 1
t

Tim Malseed

07/16/2020, 7:10 AM
Sure, tests are great. And I’m not really advocating for a ‘CompletingFlow’ type… But, tests aren’t the answer to everything. Yes, they would help to catch this error and that’s great. But just because you can write a test to catch a possible bug, doesn’t mean we couldn’t also make it harder to write the bug in the first place.
g

gildor

07/16/2020, 7:11 AM
again, I just don’t understand how such type may look like. Is it just the same Flow, but with promise in name to complete?
t

Tim Malseed

07/16/2020, 7:12 AM
Maybe?
g

gildor

07/16/2020, 7:13 AM
I understand Mono/Single/single, it’s 1 or error, Observable/Flux/Flow it’s 0..N, even Maybe it’s 0..1, but what is completing flow?
Maybe it’s just 0..1, or exactly the same as nullable suspend function
t

Tim Malseed

07/16/2020, 7:14 AM
Yeah, perhaps theres no sense in marking a Flow as ‘completable’, if that simply means it might complete in 75 years from now
o

octylFractal

07/16/2020, 7:14 AM
that can really be true for any suspending op though
is a suspend function "completable" if it calls
delay(Long.MAX_VALUE)
g

gildor

07/16/2020, 7:15 AM
it’s true, and for any other function with Thread.sleep() or something like awaitTermination()
But case when Flow is not completing is much more common than never returning function (which ususally has some clue about it in the name), just because Flow often represent stream of events and it active until source of those events exists
t

Tim Malseed

07/16/2020, 7:18 AM
I am just lamenting that there’s no way for us to codify that a flow can be expected to complete. I have written some flows that scan all the directories on the device, emitting the directory name for each one it finds. I know this completes, and I do something when it completes. And then some flows monitor a database and emit new values when the database changes - and I know these never complete. There’s no way for me to indicate that this is the behaviour of these flows.
o

octylFractal

07/16/2020, 7:18 AM
documentation comments 🙂
t

Tim Malseed

07/16/2020, 7:18 AM
Now, I know you want to ask: How would one indicate this behaviour? Again, I don’t have an answer, and I’m not suggesting the API needs to change. Just discussing.
o

octylFractal

07/16/2020, 7:19 AM
I can't think of a good way to codify it, maybe someone more experienced with language development could propose something. For now, I'm satisfied with reading documentation
t

Tim Malseed

07/16/2020, 7:19 AM
Yeah, or even just the flows variable/method name
g

gildor

07/16/2020, 7:19 AM
such way to represent completing event source doesn’t exist in any reactive library which I know
actually even things like Single/Mono/Maybe do not exist in many libraries
t

Tim Malseed

07/16/2020, 7:20 AM
Right. But I’m not quite sure what your point is. Why does it matter what other libraries do?
g

gildor

07/16/2020, 7:21 AM
More people who think about such problems, nobody ended up with solution for now, so it probably doesn’t have simple/good enough solution
t

Tim Malseed

07/16/2020, 7:22 AM
All the more reason to discuss it then
a

albertosh

07/16/2020, 7:30 AM
As soon as you start working with event based frameworks, there’s no such thing as “this 0..N will complete because of its type so I can safely put code *afterwards*” What you can do it keep going with the flow (no puns intended). Are you using any reactive library? Good, use it. Do you need something to be executed when the flow completes? Go for `onCompletion` method Are you in an Rx library? Then you have `doOnComplete` method As I read in a presentation, unless you can model everything synchronously, a single piece of asynchronous code can break your model. So model everything event based
t

Tim Malseed

07/16/2020, 7:32 AM
Yeah, I think that’s good advice. But still, forget about putting code ‘afterwards’ because of its type. The same problem still exists with
onCompletion()
- without looking at the stream, you don’t know whether this will ever be called.
I’m not trying to argue that you should be able to infer that knowledge from the type. I am simply noting that you can’t.
a

albertosh

07/16/2020, 7:33 AM
But. as mentioned before, you can’t be sure that neither • the flow will emit a limited number of items so it will complete
• The flow will complete in a reasonable amount of time
t

Tim Malseed

07/16/2020, 7:33 AM
That’s true. But we are left to look at the stream and draw these conclusions ourselves
a

albertosh

07/16/2020, 7:33 AM
Even if you had a type for that “CompletableFlow”, nothing prevents it from completing in several years
Then… I think that we’re only left with good ol’ “Use a proper name for your stuff” ¯\_(ツ)_/¯
t

Tim Malseed

07/16/2020, 7:36 AM
Yes, I agree - in fact, I made all the same points. Again, I’m just lamenting that you can’t codify this somehow. The fact that a consumer can expect a flow to complete - if you can indicate that somehow in a variable name, then I’m just entertaining the notion that you could indicate that with a type.
a

albertosh

07/16/2020, 7:36 AM
If I see a
filesInFolder
method I know for sure that it will finish in a reasonable amount of time
databaseChanges
will never finish (unless the app gets closed and some cleanup needs to be done)
time
(not sure why, but just as an example) will be there forever
Totally agree, but that happens in a lot of contexts In the end, even codifyng it into a class ends up being just a name for it
t

Tim Malseed

07/16/2020, 7:37 AM
Yeah, that’s exactly right
¯\_(ツ)_/¯
It’s a frustrating discussion because I’m not even advocating for this type
Just an interesting thought exercise
But yeah - I think the answer is that, if you can’t enforce this behaviour somehow, then there would be no point creating a type for it. If
CompletableFlow
was just a
Flow
with a different name, then you may as well just rename the variable/function.
a

albertosh

07/16/2020, 7:40 AM
In the end… I think that it’s not a matter of having an specific type or name for it. It’s a matter of the mental model that async libraries “impose” (I can’t think of a better word 😅) The same way any developer will not put anything in a finally after a
while(true)
in imperative programming, any developer with the asynchronous model in the head should not rely on putting anything after a
collect
You could go for a typealias to make it a bit for explicit
typealias CompletableFlow<T> = Flow<T>
fun listFiles(): CompletableFlow<T>
But, otherwise, everything is the same
t

Tim Malseed

07/16/2020, 7:42 AM
…should not rely on anything they put after collect being executed *
It’s OK to put code after collect - just as its OK to use
onComplete()
. But yeah, you have to have the expectation that it may never be called
Actually, a typealias is a really good suggestion for this
a

albertosh

07/16/2020, 7:48 AM
If you wanted to limit the “scope” of your
CompletableFlow
you could go for an inline class
inline class CompletableFlow<T>(private val flow: Flow<T>)
So you can have functions that only accept a
CompletableFlow
val flow: Flow<Int> = ...
val completable: CompletableFlow<Int> = ...
fun demo(c: CompletableFlow<Int>) = ...
demo(completable) // works
demo(flow) // doesn't work
I’m not sure about inline classes and generics, though
j

julian

07/16/2020, 7:56 AM
Timeout! Guaranteed to complete.
😂 1
z

Zach Klippenstein (he/him) [MOD]

07/16/2020, 2:22 PM
Now, I know you want to ask: How would one indicate this behaviour?
I think this would be a great use case for dependent types, which kotlin doesn't have and probably never will. https://en.m.wikipedia.org/wiki/Dependent_type
👍 1
g

gildor

07/16/2020, 2:25 PM
I think it’s overkill to solve this with dependent types
z

Zach Klippenstein (he/him) [MOD]

07/16/2020, 2:29 PM
Is it? This thread is a discussion of how there isn't really a good way to express the "completability" of a flow in the type system. And expressing stuff like list size in the type of the list is a basic use case for dependent types, isn't it?
g

gildor

07/16/2020, 2:36 PM
Even if something is completable in theory, it doesn’t make it completable on practice
also such things as error in potentially infinite stream also “complete” it if we talk about use case when you do something after “collect” method call
I mean it’s interesting theoretical talk for types, but I really don’t think it solvable on practice But I may be wrong
z

Zach Klippenstein (he/him) [MOD]

07/16/2020, 2:45 PM
I don't know what the solution would look like, my (very limited) exposure to DTs is with pure functional languages that don't have imperative calls at all, let alone suspending ones. But as a pattern match, the problem of "how to express some runtime property in the type system" sounds like a dependent types problem to me.
t

Tim Malseed

07/16/2020, 3:12 PM
Thanks Zach. I won’t pretend to understand anything in this article, but it’s nice to know that a language feature exists out there that might solve at least similar problems to the one I’m describing