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
p

Pat Teruel

03/10/2023, 9:28 PM
Hello! I’m developing a Mobile SDK using KMM and I would like to confirm how “dangerous” is it to use
GlobalScope.async
? Or is there an alternative way to do a
DispatchQueue.global().async
on KMM? My problem is, KMM doesn’t have a close-to-native way of Scheduling tasks without freezing the Suspend function. So I had to create a class that’s “invalidatable”, similar to that of the Timer in Swift.
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay

class AsyncSchedulerCaller(
    delayTime: Long,
    suspendFunction: suspend () -> Unit
) {
    init {
        GlobalScope.async {
            delay(delayTime)
            if (invalidated) {
                println("Invalidated.")
            } else {
                isRunning = true
                suspendFunction()
                isRunning = false
            }
        }
    }
    var invalidated = false
    var isRunning = false

    fun invalidate() {
        invalidated = true
    }
}
The way I use this is I store it in an optional variable and invalidate if it exists and create a new one, e.g.
class SomeClass { 
    var scheduler: AsyncSchedulerCaller? = null 

    suspend fun someSuspendFunction() { 
        runSomeApiCallHere() 

        scheduler?.invalidate() // this will make sure that the existing scheduled task will not be run
        scheduler = AsyncSchedulerCaller( 
            delayTime = 500, // will run after 500 milliseconds
            suspendFunction = {
                runSomeOtherApiCallHere() 
            }
        )
    }
}
To be honest, it already runs properly in iOS, and the scheduled task seem to run in the background. But I want to understand why it does, else, I might encounter bugs and I wouldn’t know how to fix. That said, it works in iOS, but I haven’t tested in Android. Would this kind of code be dangerous on the app’s lifecycle in Android? Thanks for the answers.
j

Jeff Lockhart

03/11/2023, 7:01 PM
GlobalScope.async
(although in this case I'd recommend simply
GlobalScope.launch
, as you're not needing to await an async returned value) is pretty similar to iOS's
DispatchQueue.global().async
, except it uses Kotlin's coroutines instead of GCD queues. It's only "dangerous" in that it doesn't take advantage of Kotlin coroutine's structured concurrency. `GlobalScope`'s lifecycle is the life of your app. So the coroutine's async work isn't automatically cancelled at the end of a more intentionally defined `CoroutineScope`'s lifecycle. Your code does work, but the coroutine lives longer than it needs to before determining it's no longer needed. You could do something like this instead, and explicitly cancel the running coroutine when it's invalidated:
class AsyncSchedulerCaller(
    delayTime: Long,
    suspendFunction: suspend () -> Unit
) {
    private val job = GlobalScope.launch {
        delay(delayTime)
        isRunning = true
        suspendFunction()
        isRunning = false
    }

    var isRunning = false
        private set

    fun invalidate() {
        job.cancel()
        println("Invalidated.")
    }
}
If
invalidate()
is being called from iOS, this may be the most straightforward solution. Alternatively, if you're able to define a `CoroutineScope` that is `cancel()`ed when you'd be invalidating, you could pass the scope and have the coroutine cancelled for you:
class AsyncSchedulerCaller(
    delayTime: Long,
    scope: CoroutineScope,
    suspendFunction: suspend () -> Unit
) {
    private val job = scope.launch {
        try {
            delay(delayTime)
        } catch (e: CancellationException) {
            println("Invalidated.")
            throw e
        }
        isRunning = true
        suspendFunction()
        isRunning = false
    }

    var isRunning = false
        private set
}
The advantage of using
CoroutineScope
is that you can run multiple coroutines within the scope and they will all be cancelled when the scope is cancelled at the end of its lifecycle.
b

Big Chungus

03/11/2023, 10:21 PM
Isn't freezing obsolete with new mm?
p

Pat Teruel

03/13/2023, 1:35 AM
@Jeff Lockhart Thanks for this comprehensive answer! I did realize I could actually store the
async
value into a variable and realize it's a Job type, so yeah I pretty much added the same code you did here. Another question though. Since I don't want the coroutine to live longer than it should, can I actually just "invalidate", or cancel the job INSIDE the coroutine scope after the suspend function is executed completely? or is it a bad practice to do that?
j

Jeff Lockhart

03/13/2023, 5:10 AM
Once a coroutine builder's suspend function completes, the coroutine is finished as well. So there's no need to explicitly cancel it after
suspendFunction()
completes, if I understand your question correctly. There's nothing wrong with cancelling a coroutine job from within its suspend function. But if you do need to cancel a coroutine early from within its own suspend function, it's generally easier to just return early. Cancelling a coroutine's job only works to cancel a coroutine while it's in a cancellable state, where the code is actively checking the cancelled state of the coroutine and returning early or throwing
CancellationException
in response. Well behaving long-running suspend functions, such as
delay()
, will do this for you. You can also simply throw
CancellationException
at any point in a running coroutine to cancel it. See docs on coroutine cancellation. Martynas brings up a good question. You mention needing to freeze your suspend function. Are you not using the new Kotlin/Native memory model?
p

Pat Teruel

03/14/2023, 1:54 AM
By freezing, I meant that the Suspend function has to wait for the nested suspend function to finish before the suspend function itself is finished. e.g.
suspend fun a() {
    b()
}
suspend fun b() {
    delay(1000)
}
When I do it this way,
a()
will not be finished until
b()
is finished. What I wanted to do, as I already mentioned on this thread, is to not have
a()
wait for
b()
to finish, and instead schedule
b()
to be executed IF there’s no “new”
b()
to be executed. so:
suspend fun a() {
   existingCaller?.invalidate()
   existingCaller = AsyncCaller {
        b()
   } 
}
Maybe the terms I used is wrong. But anyway, I’m using the new memory model because it’s awesome. That’s the one in the gradle properties, right?
#Native
kotlin.native.binary.objcExportSuspendFunctionLaunchThreadRestriction=none
j

Jeff Lockhart

03/14/2023, 6:00 AM
The new memory model gradle property is:
kotlin.native.binary.memoryModel=experimental
But it's enabled by default since Kotlin 1.7.20. The property
kotlin.native.binary.objcExportSuspendFunctionLaunchThreadRestriction=none
is an additional option that can be enabled with the new memory model though. The term "freezing" was just a bit confusing because the old memory model required freezing objects as read-only in order to access an object from multiple threads. I understand your intention is just to be able to replace a previously scheduled suspend routine with a new routine. 👍🏼