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
a

Allan Wang

10/14/2018, 12:13 AM
I’m still at the stage where I’m reading about coroutines rather than using it extensively, but I have a few more questions: When it comes to writing suspended functions, is there anything we should look out for in terms of potential memory leaks? If I compare Android coroutines with anko, anko tends to wrap the receiver with a weakreference, so that you can retrieve it again during your call. It’s written as type
(T) -> Unit
vs
T.() -> Unit
, which strikes me as a bit odd as anyone can use the original variable and forget about trying to get it from the weak reference. With coroutines, I don’t think weak references are used correct? Would it stand that so long as we make the coroutine scope agree to our lifecycle, we don’t have to worry about leaking variables beyond what we would normally consider when writing synchronous code? More specifically to Android, is there a general practice for writing suspended functions dealing with
Context
in a utility class where context would be passed through as an argument? Is it fine that we keep a global hashmap of deferred results if the scope cancels the job when appropriate?
g

gildor

10/14/2018, 2:32 AM
Coroutines in anko deprecated and suggest to use async directly, so not sure what you mean. Potential coroutine memory leaks are mostly the same as any other async code. Structure concurrency forces you to use some scope and in case of Android it’s your component lifecycle, so this allow to have much more robust and safe resource and memory management Because coroutine cancellation is cooperative and if every component supports it you don’t need weak reference, because Job will be cancelled and all children coroutines of this scope. But if you use coroutines just as abstraction for threading and wrapping blocking code than yes, weak reference can be useful, because you just cannot cancel blocking code during operation
More specifically to Android, is there a general practice for writing suspended functions dealing with
Context
in a utility class where context would be passed through as an argument?
Depends how you use this context. If you don’t use any non-cancellable or blocking code in your suspend utility, than everything is finy. if you do, than you have not so many choices, one common practice for that, always get applicationContext instance from any passed context, so there is not possible to leak such global context, but this work not for all cases, sometimes you need component context.
In general, I don’t see big differences in approach comparing with other async code except that only coroutines force you to use scopes and this helps to avoid common programmer’s mistakes and do not forget bind async code to lifecycle
a

Allan Wang

10/14/2018, 2:59 AM
My goal wasn’t to make an argument for anko, but to see what I might have to focus on, given anko’s different structure. I was thinking of a few examples, such as passing context into suspended functions, and creating something like RxJava’s PublishSubject for js interactions in Android. For js, I can add an interface for the webview to get onclick events, then switch to the main thread to show the onclick events in the ui. It seems like in all these cases, so long as I don’t keep a global reference, everything will be okay. It was just the fact that anko wrapped the receiver with a weak reference that made me think that I might be missing something.
g

gildor

10/14/2018, 3:55 AM
Could you show an example of such anko code? Most probably it requires only for blocking code wrapped to coroutines
given anko’s different structure.
Could you show an example?
context into suspended functions, and creating
As I said before it depends on context type (application context cannot leak) and on suspend function implementation, if all operations inside suspend function are cancelable than everything is fine even with activity context
something like RxJava’s PublishSubject
Similar approach already available in Channels API
I can add an interface for the webview to get onclick events, then switch to the main thread to show the onclick events in the ui.
But you don't need context for this task, switching of threads can be done with coroutines dispatchers
a

Allan Wang

10/14/2018, 5:31 AM
I have to take a look at channels and with coroutine dispatchers. My question towards anko is here: https://github.com/Kotlin/anko/issues/496 If it’s safe to use context within anko’s async code, why did they have to wrap it in a weak reference? Their
uiThread
method also checks if the weak reference still exists, so how does that differ with coroutines? My current logic all use view post runnables, Rx, and anko. The questions I have for coroutines are the same as I’d have for my current code, though as I make the transition I just want to make sure that I do everything properly.
g

gildor

10/17/2018, 2:04 AM
Because it depends on function, sometimes it’s safe, sometimes it doesn’t. If you have blocking operation or non-cancellalbe async than context will leak during this optetaion
Also just checked what is
doAsync
and it’s not coroutine! This is just a wrapper from ExecutorService that runs on thread executor and you cannot cancel it (you cannot just stop thread, only finish it) and such task is always blocking, so, yeah you need weak reference there
But it’s pretty different with coroutines, at least because coroutines are async and non-blocking