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
p

Paul Woitaschek

03/26/2019, 8:36 AM
I.e. that a coroutine launched in onStart will get cancelled in onStop, onCreateView -> onDestroyView, onCreate -> onDestroy; etc?
r

ribesg

03/26/2019, 9:19 AM
Usually you basically make your Activity/Fragment implement
CoroutineScope by MainScope()
and call
cancel()
in
onDestroy()
p

Paul Woitaschek

03/26/2019, 9:22 AM
And how would that cancel onStart jobs in onDestroy?
r

ribesg

03/26/2019, 9:24 AM
If you started your job with just
launch { }
or something like that in
onStart
, then it’ll die with the rest if I understood it correctly
p

Paul Woitaschek

03/26/2019, 9:26 AM
My question was how I can make stuff from onStart not die with the rest, but get cancelled in onStop?
r

ribesg

03/26/2019, 9:27 AM
Oh, you want something specific to each lifecycle ‘level’? Then you’ll have to do it yourself
p

Paul Woitaschek

03/26/2019, 9:27 AM
And how could I do that by myself?
r

ribesg

03/26/2019, 9:28 AM
You could define multiple scopes with nested jobs I suppose, but I’m not fluent enough in coroutines
`Job`s can have parent `Job`s, I think you’ll need to play with that and make a tree of jobs
I usually just don’t care about things surviving between
onStop
and
onDestroy
... You just have to be sure that there’s nothing left after
onDestroy
. Are you sure the gains are worth the complexity of what you want to do?
p

Paul Woitaschek

03/26/2019, 9:32 AM
Sure I am
I.e. I clear my views in onDestroyView, so I don't want a coroutine I started in onCreateView access null views after onDestroyView
r

ribesg

03/26/2019, 9:34 AM
I usually make things nullable and use calls like
view?.something
so that it’s automagic
p

Paul Woitaschek

03/26/2019, 9:35 AM
Nah, that hides bugs
r

ribesg

03/26/2019, 9:35 AM
I agree that it’s not perfect but I don’t have the time for the complex task you’re talking about. But I guess you could implement all that in subclasses of
Activity
and
Fragment
and then use that
p

Paul Woitaschek

03/26/2019, 9:36 AM
I want my code to be correct and not be constantly checking for conditions I didn't write the code to run in
r

ribesg

03/26/2019, 9:37 AM
I’m still getting lost between scopes, jobs, context, dispatchers from time to time so I don’t feel I’m ready to implement such thing properly. It would take some time and not be guaranteed to work any better. Once I understand everything more I guess I’ll do something like that. Or once everything explodes 😛
Thinking about it, it seems very complex. For example my Presenter just have a reference to the Fragment/Activity, which is a CoroutineScope, and that’s how my Presenter launches coroutines. But in your case you’ll have to pass 3 or 4 scopes to the Presenter, or maybe make them accessible in the Fragment/Activity, and chose carefully which one to use every time...
p

Paul Woitaschek

03/26/2019, 9:47 AM
Job is just an interface. I can just create a base class and keep a map of <LifecycleEvent, Job> and just return the correct job depending on the lifecycle.
Wouldn't that work?
r

ribesg

03/26/2019, 10:06 AM
Hmmm maybe yeah
Make sure you look at how Job cancellation works, I think you need `SupervisorJob`s
Children of a supervisor job can fail independently of each other.
If you use basic `Job`s any error would cancel everything
s

streetsofboston

03/26/2019, 12:27 PM
I.e. I clear my views in onDestroyView, so I don't want a coroutine I started in onCreateView access null views after onDestroyView
@Paul Woitaschek A Fragment is a Lifecycle owner and its lifecycle is per default tied to the Fragment itself. This my cause problems as you described above. Instead of this:
viewModel.liveData.observe(this, Observer { ... } )
}
Do this
viewModel.liveData.observe(viewLifecycleOwner, Observer { ... } )
}
where
this
is replaced by
this.viewLifecycleOwner
This makes sure the LiveData observer will not get callbacks on dead Fragments and only when Views have been created properly, ie between onViewCreated and onViewDestroyed.
p

Paul Woitaschek

03/26/2019, 3:35 PM
I don't use LiveData
s

streetsofboston

03/26/2019, 3:39 PM
You then could tie the
viewLifecycleOwner
to your own life-cycle observers, which could guard against encountering null values for your views in your Fragments.
p

Paul Woitaschek

03/26/2019, 3:58 PM
I'm not talking about any observers, I'm talking about CoroutineScope
s

streetsofboston

03/26/2019, 4:01 PM
You could tie your CoroutineScope to this lifecycle-owner, making your CoroutineScope a life-cycle observer.
d

Dico

03/27/2019, 3:48 PM
I was looking for some kind of "activity observer" the other day to help solve problems like this
It seems like you can't listen for those events given an instance of
Activity
sadly
someone please correct me because I hope I'm wrong
s

streetsofboston

03/27/2019, 5:03 PM
d

Dico

03/27/2019, 5:03 PM
oh Awesome!
j

Jemshit Iskenderov

04/11/2019, 1:14 PM
You could create multiple
coroutineScope
properties (not implement them) that gets cancelled on different lifecycle event, then every
.launch
will use correct version of
coroutineScope
. But don’t rely on
job.cancel()
, it will cancel parent job and children, but your “computation” code will still continue to run (null view access might be done after cancelled). So
parentJob.isActive
check should be done. @Paul Woitaschek
s

streetsofboston

04/11/2019, 1:20 PM
If you use
LiveData
in your ViewModel, your Activity's or Fragment's observers should never get notified when View references are null. It's true, Jobs are cancelled only at suspension points, not just anywhere in the code. Either rely on those points or query the
isActive
property and bail out.