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
u

ursus

11/10/2019, 7:09 PM
How do you guys handle coroutines in android, which want to outlive the viewmodel scope? should repository or whatever does the couroutine have its scope, and be transparent to the viewmodel or should that scope be passed into the viewmodel and viewmodel launches the coroutine into that scope?
o

octylFractal

11/10/2019, 7:14 PM
the scope should be tied to some lifecycle, so probably the repository should have it, if it is the one that should own the coroutines
u

ursus

11/10/2019, 7:18 PM
okay, but how can I make it composable in the viewmodel?
fun Service.doWhatever() {
    serviceScope.launch {
    ...
    }
}
fun ViewModel.buttonClick() {
   viewModelScope.launch {
       service.doWhatever()
       ui.displaySuccess()
   }
}
in this ssample ui.displaySuccess wont wait for the coroutine
o

octylFractal

11/10/2019, 7:19 PM
then it probably shouldn't be in its own scope? that particular coroutine doesn't need to outlive the VM scope
u

ursus

11/10/2019, 7:20 PM
why not? say its posting a chat message, you still want the post to finish without cancel, when you switch screens, no?
o

octylFractal

11/10/2019, 7:21 PM
sounds like you need an application level scope then, that the original launch occurs on. in this case, the Service does not want to own the coroutine, but the application as a whole
u

ursus

11/10/2019, 7:22 PM
thats no difference in this case as Service is singleton, anyways where would your app scope live? or rather where its going to be used, in service or vm?
o

octylFractal

11/10/2019, 7:22 PM
I'm not sure, I'm not very familiar with android. I would use it in the VM, because that's the UI area
u

ursus

11/10/2019, 7:23 PM
so youd pass the appScope via ctor to the vm?
o

octylFractal

11/10/2019, 7:23 PM
yea
u

ursus

11/10/2019, 7:23 PM
okay, but, now viewmodel decides the scope, is that smart? client code basically dictating the lifecycle implicitly?
o

octylFractal

11/10/2019, 7:25 PM
I'm not sure about the particular design pattern pros/cons, this appears to be reasonable to me because the action is supposed to outlive the VM in this case, so you want whatever creates it to pass something in, since it (the creator) typically has a longer lifecycle than the VM
u

ursus

11/10/2019, 7:27 PM
yea but why not hide it inside the Service, or whatever holds the coroutine .. I mean for viewmodel, viewmodelScope is also private in the VM, view which has even shorter lifecycle, doesnt see it
o

octylFractal

11/10/2019, 7:28 PM
it doesn't make sense to me, because then the service would be calling out to the UI
u

ursus

11/10/2019, 7:28 PM
what do you mean? viewmodel.scope { service.foo; ui.display }
o

octylFractal

11/10/2019, 7:29 PM
then that's still on the VM scope, right?
u

ursus

11/10/2019, 7:29 PM
well, that was my argument, that each component that has a lifecycle, should have its own scope
service -> viewmodel -> view
each have their lifecycle, narrowing to the right
o

octylFractal

11/10/2019, 7:30 PM
well, it doesn't make sense, because the outer coroutine is what needs to be launched on it
so you still need to pull it out of the service
u

ursus

11/10/2019, 7:30 PM
well, why then the view doesnt own the scope if its the actual callsite?
o

octylFractal

11/10/2019, 7:31 PM
because then it should be cancelled when the view is closed, right?
u

ursus

11/10/2019, 7:31 PM
also,
fun Viewmodel.buttonClick {
   appScope.launch {
      service.foo()
      ui.display
   }
}
doesnt this leak Ui?
o

octylFractal

11/10/2019, 7:31 PM
yes, it does leak it until the coroutine finishes
there isn't much you can do to avoid that, it would leak regardless
u

ursus

11/10/2019, 7:31 PM
well yes, and you dont want that cancelation, hence you move the scope ownership upstream
o

octylFractal

11/10/2019, 7:32 PM
that's not a thing in coroutines afaik
where you launch it, is what scope it is tied to
u

ursus

11/10/2019, 7:35 PM
so how would I jump that?
I dont feel like UI should decide lifecycle of some mutating business logic
o

octylFractal

11/10/2019, 7:37 PM
I suppose you could pass some event back and forth in this case
the trick is that, imo, the service shouldn't directly call the UI either
u

ursus

11/10/2019, 7:38 PM
yea sure, service has no knowledge about ui
okay so if that function will be nonsuspending, and launching a coroutine inside its service scope, how can I let the result go outside? channel?
but that breaks composability doesnt it?
o

octylFractal

11/10/2019, 7:40 PM
really, I haven't run in to this case myself, so I'm not sure what is the best/better design option. I think what I originally proposed is the best fit for this scenario, UI should dictate service lifecycle because it needs to run something after it.
u

ursus

11/10/2019, 7:46 PM
how about that leak though? thats not cool
o

octylFractal

11/10/2019, 7:47 PM
do you expect it to not "leak"?
how else will the UI object be around for when it finishes?
I would not consider it a leak, because you really do want it to stay around for later
u

ursus

11/10/2019, 7:55 PM
well youre keeping the ui in memory after it should be destroyed / gced
o

octylFractal

11/10/2019, 7:56 PM
no, because you wanted to call it
did you not want that at the end of the coroutine?
u

ursus

11/10/2019, 8:31 PM
I did, but when ui is gone, its no longer necessary. Why im beating at this is that with rxjava you can do this via autoConnect, downstream just unsubscribes, upstream keeps chugging
o

octylFractal

11/10/2019, 8:32 PM
okay, but when that
launch
block finishes... UI is GC'd
it doesn't stick around after the coroutine is done
k

kevindmoore

11/10/2019, 9:55 PM
suspend fun Service.doWhatever() {
}
fun ViewModel.buttonClick() {
   viewModelScope.launch {
       service.doWhatever()
       ui.displaySuccess()
   }
}
Couldn't you do something like this?
o

octylFractal

11/10/2019, 9:57 PM
the issue is that the coroutine should stick beyond VM, whereas this will be cancelled when the VM is closed
k

kevindmoore

11/10/2019, 10:01 PM
I see. Seems like you would start the service on it's own and then send an event back to a listener (in this case the ViewModel) that the data is ready. If the ViewModel's lifecycle is done, it would unsubscribe and not be notified
u

ursus

11/10/2019, 11:40 PM
Well yes, but youre comunicating via listener / channel / rx observsble, i.e. composability of suspend functions is gone, right?, also the listener needs to be keyed to identify that call if need be, etc. im not super happy about that
g

gildor

11/11/2019, 12:52 AM
If you want to avoid cancellation of service operation, it should be one of two: 1. implementation details of service, which never cancel operation, so just run it on own scope (for example by launching async) and awaits it already on caller's scope (just suspend function) 2. call site runs operation with NonCancellable context, but careful with second approach, it's relatively easy to leak coroutine
u

ursus

11/11/2019, 1:49 AM
1. how would that look like?
suspend fun foo() {
    val deffered = scope.async {
      // foo stuff
    }
    return deffered.await
}
this?
g

gildor

11/11/2019, 2:29 AM
yes, like this
Check this example https://pl.kotl.in/peLtoh5bh
u

ursus

11/11/2019, 5:18 AM
sorry that opens my previous snippet and a helloworld in incognito mode
g

gildor

11/11/2019, 6:01 AM
Yeah, looks like some bug of playground. Try this one: https://pl.kotl.in/wdzhx7_IY
u

ursus

11/11/2019, 6:09 AM
Yea that I had in mind, however have you seen this?
If you need to launch a coroutine that keeps running after your function returns, then make your function an extension of CoroutineScope or pass scope: CoroutineScope as parameter to make your intent clear in your function signature. Do not make these functions suspending:
https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055
g

gildor

11/11/2019, 6:17 AM
It's an explicit way to do this, as I said, it depends on what is your goal. If you just do this on-call site, of course, use different more global scope, how was already suggested in this thread if it actually services logic (do not lose requests even if client is cancelled) and you do not want to add this logic on every client, then do this on level of service, it doesn't violate structured concurrency
And what you cited is not really your case, because you want to wait for result