https://kotlinlang.org logo
Join the conversationJoin Slack
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
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
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
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 Linen
coroutines
  • j

    Jonathan Walsh

    08/06/2019, 4:24 PM
    I'm trying to use
    suspendCoroutine
    within a
    withTimeout
    call, but the timeout doesn't seem to work. Has anyone run into similar issues?
    l
    g
    • 3
    • 8
  • a

    Aldo Wachyudi

    08/06/2019, 5:24 PM
    message has been deleted
    m
    • 2
    • 3
  • d

    Derek Berner

    08/06/2019, 7:25 PM
    Is there a better way to do memoization?
    import kotlinx.coroutines.*
    
    @JvmName("_memoize_receiver")
    fun <T,R> (suspend (T) -> R).memoize(): suspend (T) -> R {
        val memos = mutableMapOf<T, Deferred<R>>()
        val f = this
        return { t ->
            coroutineScope {
                withContext(coroutineContext + <http://Dispatchers.IO|Dispatchers.IO>) {
                    synchronized(memos) {
                        memos.computeIfAbsent(t) { async { f(t) } }
                    }
                }.await()
            }
        }
    }
    
    fun <T,R> memoize(f: suspend (T) -> R): suspend (T) -> R = f.memoize()
    j
    y
    a
    • 4
    • 7
  • p

    Pablichjenkov

    08/06/2019, 7:59 PM
    I have the code bellow:
    suspend fun doSomethingAndThrow() { throw(MyException()) }
    
    val coroutineScope = CoroutineScope(Job())
    
    coroutineScope.launch {
      
      try { doSomethingAndThrow() } catch(exception: Exception) { Log.d("MyException got caught")  }
    
    }
    Is the exception thrown in the suspended fun doSomethingAndThrow(…) caught by my try/catch block or it gets caught through the CoroutineScope hierarchy. What would be a good practice to catch this exception?
    l
    s
    • 3
    • 5
  • a

    Animesh Sahu

    08/07/2019, 3:35 AM
    Is there another use of suspend functions other than delay()? I don't get it which function can be used in suspend to actually suspend it. For example if i call any api or something it will definitely block the coroutine right? So how should i use coroutine there so i can do something till the response is recieved from the server?
    g
    u
    s
    • 4
    • 10
  • h

    hyunghui

    08/07/2019, 10:16 AM
    I’m planning to implement
    rx's take(1)
    with coroutine. Is there a good way to do it? for example, run 10 random jobs and wait only until the fastest job finishes.
    g
    • 2
    • 2
  • d

    Dias

    08/07/2019, 12:36 PM
    what are the Flow use-cases? is it mostly to replace reactive streams and all of it's implementations?
    j
    e
    • 3
    • 3
  • r

    Ruckus

    08/07/2019, 2:18 PM
    Out of idle curiosity, is there any plans to expand the functionality of
    kotlinx-coroutines-javafx
    to provide helpers for common patterns, or is it only meant to provide a UI context?
    ➕ 1
    👀 1
    a
    g
    • 3
    • 13
  • a

    aerb

    08/07/2019, 3:11 PM
    is there a way to assert which dispatcher you’re on?
    d
    g
    • 3
    • 9
  • a

    aerb

    08/07/2019, 3:12 PM
    to enforce
    io
    or
    main
    for example?
    d
    • 2
    • 3
  • f

    fangzhzh

    08/07/2019, 9:44 PM
    Hi, I did search in this channel, and google, but not found. SO my question is
    kotlin
    //
        var subject = PublishSubject.create<Location>()
    
     subject
                .buffer(1L, SECONDS)
                .subscribe( {
                list ->
                   list.lastOrNull()?.let {}
                }, {}, {})
    The subscribe's on Next is called every 1 second, and it process only the first one. This is helpful that I have too many log and I just want print every seconds How I do it in coroutines? Thanks
    d
    g
    • 3
    • 51
  • w

    Wilson Castiblanco

    08/07/2019, 11:20 PM
    Hello guys! I have these two implementations in a
    DeepLinkPresenter
    . Which of those are the "best" approach having in mind the CoroutineScope implementation.
    d
    • 2
    • 1
  • a

    addamsson

    08/08/2019, 9:11 AM
    How can I block while a coroutine is running? My use case is that I'm confining operations to one thread in a class which has shared mutable state so I have to use a single threaded coroutine dispatcher, but I also want to provide a synchronous interface for my users. How can I do this?
    j
    g
    +3
    • 6
    • 23
  • s

    sam

    08/08/2019, 7:44 PM
    What’s the best way to mix a long running loop with coroutines. For example, I want to do something like
    while (true) { consumer.take() }
    , where consumer.take is a blocking call on a JMS client. Normally, I’d launch a new thread for this, and then shut down the thread once the program exits.
    o
    l
    • 3
    • 28
  • m

    Marko Mitic

    08/08/2019, 9:06 PM
    Latest Room alpha has Flow support http://commonsware.com/blog/2019/08/08/room-flow.html
    m
    • 2
    • 4
  • g

    groostav

    08/08/2019, 9:36 PM
    hmm. I'm curious about the
    Job
    and parent-child'ing.
    suspend fun doLongRunningWork {
      val myContext = coroutineContext
      requireNotNull(myContext[Job])
    
      val async1 = someScope.async { 
        //...
      }
      val async2 = someScope.async(myContext) {
        //...
      }
    
      //maybe this code joins on async1 & async2, maybe not. should that impact my approach?
    }
    the latter exerts a rather strange back-pressure on the callers coroutine-entrypoint. Why the distinction?
    z
    g
    l
    • 4
    • 27
  • r

    rook

    08/08/2019, 9:44 PM
    I’m trying to make a
    suspend
    function execute its contents on a specific dispatcher. So far:``` suspend fun getFoo(): Foo? = coroutineScope { withContext(Dispatchers.IO) { retrieveFoo() } }``` Is this the best way to go about it?
    o
    g
    e
    • 4
    • 9
  • j

    jkbbwr

    08/09/2019, 12:43 PM
    Is there a way to send a value to a continuation. (not channels)
    d
    d
    • 3
    • 3
  • a

    Aslam Hossin

    08/09/2019, 4:40 PM
    How to repeat a task within a duration of delay using coroutines in Android?
    i
    m
    +2
    • 5
    • 15
  • k

    kevinherron

    08/09/2019, 5:08 PM
    anybody know if support for declaring anonymous suspending functions is coming?
    s
    • 2
    • 3
  • k

    kevinherron

    08/09/2019, 5:09 PM
    or suspending lambdas i guess
    j
    b
    s
    • 4
    • 13
  • v

    Vsevolod Tolstopyatov [JB]

    08/09/2019, 6:32 PM
    📣 📣 📣
    kotlinx.coroutines
    1.3.0-RC2 is here! Changelog: * New flow operator families *
    combine
    and
    combineTransform
    *
    flatMapLatest
    ,
    mapLatest
    ,
    transformLatest
    and
    collectLatest
    * R8-friendly
    ServiceLoader
    usage to enable SL optimization on Android toolchain 3.6.0+ * Stacktrace recovery for minified Android builds * Full-blown interop between coroutine context and Reactor context * Various fixes and improvements * Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.3.0-rc2
    👏 22
    👍 3
    🐿 2
    👀 3
    🍻 1
    🎉 5
    😒uspend: 3
    a
    s
    • 3
    • 16
  • b

    bogdoll

    08/10/2019, 8:27 AM
    For working non blocking the AWS2 SDK provides methods which returns CompleteableFuture<T>. Wrapping them into coroutines I wrote the following extension function (I don't like the name). My question would be, is that extension okay, or even already implemented in the standard coroutines library? If that extension is okay, what would you suggest as name for it?
    suspend fun <T> CompletableFuture<T>.suspending() : T = suspendCoroutine { cont ->
        whenComplete { v, e -> if(e==null) cont.resume(v) else cont.resumeWithException(e) }
    }
    It can be used for example to wrap the following AWS SDK method:
    CompletableFuture<CopyObjectResponse> copyObject(CopyObjectRequest copyObjectRequest)
    into
    suspend fun S3AsyncClient.suspendingCopyObject(copyObjectRequest: CopyObjectRequest) : CopyObjectResponse = copyObject(copyObjectRequest).suspending()
    s
    d
    • 3
    • 4
  • v

    voddan

    08/10/2019, 10:17 AM
    what does
    BOM
    in the new
    kotlinx-coroutines-bom
    stand for?
    m
    g
    • 3
    • 4
  • s

    sjthn

    08/10/2019, 5:38 PM
    Hi all, I am using the following scope to launch the coroutine on button click. But the app crashes w/o any logs. Do you know what I am missing?
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        presenter = ProductPresenter(ProductRepository(Network(), Database()), scope)
    
        button_fetch.setOnClickListener {
            presenter.onFetchClick()
        }
    }
    
    ---------------------------------------------------------------------
    
        fun onFetchClick() {
            loadingState.value = true
    
            scope.launch {
                //...
            }
        }
    l
    • 2
    • 5
  • r

    Robert Menke

    08/11/2019, 1:43 AM
    Just want to say thank you to whoever put https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/01_Introduction together. That was a really useful tutorial and I appreciate the work that went into it!
    👍 4
    e
    • 2
    • 1
  • k

    Kulwinder Singh

    08/11/2019, 9:39 AM
    Hi, can i convert this Firebase Phone Auth code to coroutines friendly, in below method i have two options first is that i can scope this call to activity and second is that i can add some Executor(which i don't know how works). but here i don't want this request to be scoped on Activity because i don't want this request inside Activity instead i want to move it inside ViewModel or Repository.
    phoneAuth.verifyPhoneNumber(
    number, 1, TimeUnit.MINUTES,
    executor or Activity // but here i don't wanna scope it to activity instead i want to use it inside ViewModel using coroutines
    ,authCallback)
    l
    g
    • 3
    • 8
  • d

    dharrigan

    08/11/2019, 12:14 PM
    If I have, lets say 3 functions that write to a database. They are independent of each other (in that the writes of one function does not affect the writes of another function into the db) and I want to run each in their own coroutine, not caring about any return code or status.
    m
    u
    g
    • 4
    • 24
  • d

    dharrigan

    08/11/2019, 12:15 PM
    Which of these two approaches would be better? (and are they idomatic?)
    m
    g
    • 3
    • 5
  • d

    dharrigan

    08/11/2019, 12:15 PM
    fun doSomething() = GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        writeIntoTable1()
        writeIntoTable2()
        writeIntoTable3()
    }
    
    suspend fun writeIntoTable1() {...}
    suspend fun writeIntoTable2() {...}
    suspend fun writeIntoTable3() {...}
    g
    d
    • 3
    • 7
Powered by Linen
Title
d

dharrigan

08/11/2019, 12:15 PM
fun doSomething() = GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    writeIntoTable1()
    writeIntoTable2()
    writeIntoTable3()
}

suspend fun writeIntoTable1() {...}
suspend fun writeIntoTable2() {...}
suspend fun writeIntoTable3() {...}
g

gildor

08/11/2019, 2:29 PM
okay, there are a few layers in this question 1. First option will run writes in parallel, second sequentially, choose what is suits your use case better 2. Implementing doSomething in a such way is a very bad approach, especially with GlobalScope. Instead, I would just make doSomething suspendable and use
coroutineScope {}
to group writes, so client could launch this suscpend function in own scope using launch, or just call suspend function (which is even better) 3. To make parallel version of this code less awkward I would use something like:
listOf(::writeIntoTable1, ::writeIntoTable2, ::writeIntoTable3).forEach { launch ( it() } }
Or any other way to group operations and do not copy paste invocation strategy 4. i see that you use IO dispatcher which looks suspicious in this case, because you call suspend function which itself never should block, so if write is blocking, just move this IO dispatcher to those functions or make them blocking explicitly, remove suspend modifier and add Blocking suffix
d

dharrigan

08/11/2019, 3:51 PM
thanks for the great tips! 🙂
d

Dico

08/11/2019, 10:33 PM
What is Blocking suffix?
@gildor
g

gildor

08/12/2019, 3:50 AM
I mean if
writeIntoTableN
is blocking better to remove suspend modifier which is probably useless and rather confusing for blocking function and rename it to writeIntoTableBlocking, so it will be clear that function is blocking and should be called from corresponding context
d

Dico

08/12/2019, 9:38 AM
Oh name suffix of course, I'm an idiot
I thought you meant there's some kind of unified marker thing
View count: 3