https://kotlinlang.org logo
Docs
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

    Joan Colmenero

    10/27/2019, 8:16 PM
    Anyone of you can give me other approach of this:
    class ContentPresenter(
            private val useCase: ContentUseCase,
            private val contextPool: CoroutineContextProvider = CoroutineContextProvider()
    ) {
    ....
    open class CoroutineContextProvider {
        open val Main: CoroutineContext by lazy { UI }
        open val IO: CoroutineContext by lazy { CommonPool }
    }
    Then inside of each presenter I'm doing
    launch(contextPool.Main) {
                val content = withContext(<http://contextPool.IO|contextPool.IO>) {
                    repository.requestContent()
                }
                view.displayContent(content)
            }
    On every presenter I'm passing the
    CoroutineContextProvider
    in order to test it with
    unit testing
    then for testing I have the
    TestCouroutineContextProvider
    which I use
    Unconfined
    , the thing is, do you guys are you using something like
    AbstractPresenter
    where you have there the
    Job
    and then you only from the presenter call it? I'd like to abstract it a little bit, and then could use my presenter without passing the
    CoroutineContextProvider
    via parameter, and then use it also in
    unit testing
    . Could you help me out with this?
    t
    • 2
    • 1
  • m

    Mani

    10/28/2019, 1:04 PM
    Folks, quick help. Is this a right way?
    slackIncomingHook.sendText(SlackMessage("Attempting RTS for son's of length: ${stockOutwardNoteIds.size}, warehouseId: ${warehouse.id()}"))
    stockOutwardNoteIds.map {
             async {
                               warehousing.packStockOutwardNote(warehouse.id(), it)
                               freshRTSHelper.markRTSForFreshOrder(warehouseId = warehouse.id(), stockOutwardNoteId = it)
                        }
             }.awaitAll()
    m
    • 2
    • 8
  • s

    sdeleuze

    10/28/2019, 1:51 PM
    What is the best practice to use Coroutines (my use case is Fetch API +
    await()
    on the returned
    Promise
    ) in JavaScript callbacks like
    onclient =  { }
    ? cc @Vsevolod Tolstopyatov [JB]
    👀 1
    z
    g
    v
    • 4
    • 11
  • i

    itnoles

    10/28/2019, 8:13 PM
    Should I use Coroutines or Flow for Twitter4j?
    🤔 3
    e
    g
    • 3
    • 3
  • j

    Joan Colmenero

    10/28/2019, 9:42 PM
    This
    open class CoroutineContextProvider {
        open val Main: CoroutineContext by lazy { UI }
        open val IO: CoroutineContext by lazy { CommonPool }
    }
    Is the same as :
    open class CoroutineContextProvider {
        open val main: CoroutineContext by lazy { Dispatchers.Main }
        open val IO: CoroutineContext by lazy { <http://Dispatchers.IO|Dispatchers.IO> }
    }
    I was using experimental coroutines and now I have to update them
    t
    k
    g
    • 4
    • 5
  • m

    Marcin Gryszko

    10/29/2019, 6:20 AM
    I'm trying to dig into the internal implementation of JVM coroutines. How a coroutine block (instantiated as
    SuspendLambda
    resumes its execution after last suspension point when
    invokeSuspend
    is called again? Is the magic field
    L$0
    inside
    SuspendLambda
    responsible for this? I'm working with a dead-simple snippet to understand the inner workings:
    fun main() {
      val i = runBlocking {
        delay(1000)
        1
      }
      println(i)
    }
    s
    e
    • 3
    • 2
  • g

    groostav

    10/29/2019, 9:26 PM
    is it possible to put something in a
    coroutineContext
    with a
    finalize
    that can detect an abandoned coroutine? Maybe print a warning?
    e
    o
    l
    • 4
    • 24
  • j

    James

    10/29/2019, 11:08 PM
    are Coroutines suitable for a resource-level-lock of some kind? Trying to implement a resource locking system where any of those resources can be modified concurrently, but if that resource is already locked then the Coroutine should suspend until the lock is available. This is what I have so far, but I feel like this is a really naive way of doing things. Any suggestions on how to improve this? I'm managing the Set from a single thread since I'm fairly sure that a MutableSet (LinkedHashSet) is not thread safe
    g
    m
    o
    • 4
    • 20
  • p

    Paulius Ruminas

    10/30/2019, 8:14 AM
    Hello, we have a gps location service that we create using dagger and we are getting an exception that
    _location
    channel was closed and we are not sure how can this happen since
    _location
    is a private member and there is no call to
    _location.close()
    . What are we missing? Dagger
    @Provides
        @Singleton
        fun gpsLocationService(): GpsLocationService = GpsLocationService(
            context = context,
            coroutineContext = Dispatchers.Default
        )
    Service
    class GpsLocationService(
        private val context: Context,
        override val coroutineContext: CoroutineContext
    ) : CoroutineScope {
    
        private val logger = Logger.get(this::class)
    
        private val _location = BroadcastChannel<Location>(1)
    
        private val interval: Millis = GpsUpdateInterval.High.interval
    
        private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
    
        private val locationCallback: LocationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                if (GpsHelper.isGpsEnabled(context)) {
                    logger.trace("Location acquired (${locationResult.lastLocation}).")
                    _location.sendBlocking(locationResult.lastLocation)
                } else {
                    logger.trace("GPS is disabled, ignoring location change.")
                }
            }
        }
    
        suspend fun requestLocation(): Location? = _location.openSubscription().consume {
            val location = withTimeoutOrNull(15.seconds) { receiveOrNull() }
    
            location
        }
    }
    b
    • 2
    • 10
  • n

    Nikky

    10/30/2019, 10:17 AM
    in kotlin-js how do i launch a coroutine from normal code without using GlobalScope ? using that exceptions get lost apparently ? is there a better thing ?
    e
    f
    d
    • 4
    • 14
  • m

    Manuel Vivo

    10/30/2019, 10:55 AM
    What's the recommended way to refer to a conflated channel:
    private val channel = ConflatedBroadcastChannel<T>
    or
    private val channel = BroadcastChannel<T>(Channel.CONFLATED)
    ?
    l
    • 2
    • 2
  • a

    AJ Alt

    10/30/2019, 6:24 PM
    I want to write a function that takes a suspend lambda and returns a custom future type, like
    CoroutineScope.future
    or
    rxSingle
    functions from the integrations libraries. Those functions are all implemented with
    AbstractCoroutine
    , which is marked as internal. Is there a recommended way to implement that type of functionality without internal classes, or is there no way around internal APIs a the moment?
    i
    o
    d
    • 4
    • 18
  • p

    Paul Woitaschek

    10/30/2019, 8:55 PM
    Huh, what's happening here?
    @Test
      fun experiment() = runBlockingTest {
        PublishProcessor.create<Unit>()
          .replay(1)
          .refCount()
          .asFlow()
          .first()
      }
    This fails with
    java.lang.IllegalStateException: This job has not completed yet
    oO Can someone explan this?
    s
    v
    • 3
    • 6
  • d

    danny

    10/30/2019, 11:54 PM
    Is there an issue I can track for improvements to the dispatchers scheduling behavior? Still looks like it very aggressively wakes threads and burns a ton of CPU when just a couple of threads could handle the workload (don't see anything here for a while now https://github.com/Kotlin/kotlinx.coroutines/issues/840)
    k
    • 2
    • 3
  • l

    louiscad

    10/31/2019, 7:00 AM
    @Yauhen Pelkin You probably just need to use
    combine
    .
    o
    b
    • 3
    • 3
  • k

    Khan

    10/31/2019, 9:47 AM
    Hi. I have to clear db when exit fragment. I am creating a coroutine to clear db table inside viewmodel onCleared. As you can see i am not using viewModelScope because my table will not be cleared and coroutine will be cancelled. Do you think its fine to use CoroutineScope here?
    Untitled
    m
    p
    • 3
    • 11
  • a

    Alexjok

    11/01/2019, 9:07 AM
    Hello, how i can do something like that
    suspend fun test() {
    async {  someWork()  }
    }
    How call async inside suspend fun?
    g
    • 2
    • 8
  • j

    Jonathan Mew

    11/01/2019, 9:52 AM
    To keep things simple until we have a need for something more complex, we run controller code as blocking (using ktor). With that in mind, if I'm calling into a suspend function in a 3rd party library that makes network calls, is this a reasonable construct to use?
    runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
        try {
            thirdParty.doNetworkStuff()
        } catch (e: Exception) {
            log.warn("recoverable error", e)
        }
    }
    g
    e
    • 3
    • 40
  • r

    Robert Jaros

    11/01/2019, 1:24 PM
    Why in this code the exception is printed only once: https://pl.kotl.in/TZrPEdnso If I change
    launch
    to
    GlobalScope.launch
    the exception is printed twice: https://pl.kotl.in/13sfoRVtk Shouldn't the unhandled exception cancel the job in both cases?
    s
    b
    • 3
    • 13
  • a

    Adam Powell

    11/01/2019, 2:06 PM
    Is the example posted at https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-unconfined.html correct? How can it print
    1 3 2
    given that
    withContext
    returns the
    T
    from the block, which would be the
    Unit
    from executing
    println(2)
    first?
    p
    • 2
    • 1
  • u

    ubu

    11/01/2019, 11:56 PM
    Hi there. I have a
    Flow
    emitting
    1
    ,
    2
    ,
    3
    . Is there a way to transform this flow to emit:
    [1]
    ,
    [1,2]
    ,
    [1,2,3]
    . I know there’s this
    fold
    operator, but it’s terminal. In my case I need a value to be emitted on each accumulation step. Is there any appropriate operator out-of-the-box?
    o
    z
    • 3
    • 5
  • n

    Nav Singh

    11/02/2019, 4:51 AM
    Hi Folks, I am trying to implement the Structured concurrency using Coroutines.... I fire 2 network calls parallel they work fine....but I have a use Case that I need to cancel one of the them as soon as I get failure response for one of them . Any suggestions appreciated Thanks
    o
    z
    • 3
    • 16
  • a

    alexsullivan114

    11/02/2019, 8:33 PM
    Flow/Coroutines question: I'm trying to migrate from RxJava to Flow for Android apps. I often write apps where in some starting point of the app (onCreate or the ViewModel init function for example) I subscribe to a bunch of observables. So, a typical
    init
    of a view model of mine may look like this:
    init {
        myObservable
            .filter { whatever() }
            .map { whatever() }
            .subscribe { pushToMySubject() }
    
        myOtherObservable
            .filter { whatever() }
            .map { whatever() }
            .subscribe { pushToMyOtherSubject() }
    
        myThirdObservable
            .filter { whatever() }
            .map { whatever() }
            .subscribe { pushToMyThirdSubject() }
    }
    But when using flow, we can only call
    collect
    (which if I'm not mistaken is analagous to
    subscribe
    in RxJava) from within a coroutine context, which makes sense. But, as far as I can tell, calling
    collect
    blocks that coroutine context (my terminology might be garbage here) so you can't really have the above setup because we wouldn't execute the last two subscribes until the first observable completes. So two questions: 1. Is my understanding correct? 2. What's the preferred path to handle this sort of scenario?
    o
    d
    e
    • 4
    • 14
  • k

    Khan

    11/02/2019, 11:56 PM
    If i start a coroutine with CoroutineScope inside ViewModel (which is doing some db operation but this operation doesn’t return anything. So coroutine starts performs db operation and completes). During this operation if my viewmodel onCleared() is called but i don’t cancel coroutine will my viewmodel leak?
    o
    a
    s
    • 4
    • 10
  • k

    Kroppeb

    11/03/2019, 2:09 AM
    I want to select between 2
    Deferred<V>
    but only fail if both fail. Would this work/is there a better way to do it?
    d
    o
    • 3
    • 7
  • s

    scottiedog45

    11/03/2019, 3:22 PM
    What’s the difference between these two syntaxes?
    val scope = CoroutineScope(errorHandler)
    scope.launch {
        throw SomeSillyException()
    }
    
    val scope = CoroutineScope()
    scope.launch(errorHandler) {
        throw SomeSillyException()
    }
    d
    s
    e
    • 4
    • 7
  • w

    william

    11/03/2019, 6:19 PM
    anyone have suggestions for getting started with coroutines for an rxjava user?
    d
    e
    • 3
    • 3
  • v

    Vincent Williams

    11/03/2019, 7:25 PM
    I assume you would just call
    collect { }
    in the unit test and then verify that the correct item comes through, however this throws
    IllegalStateException: This job has not completed yet
    m
    o
    +2
    • 5
    • 26
  • s

    Stephan Schroeder

    11/04/2019, 11:17 AM
    So I was thinking about parallel mapping. So basically having an extension function like this:
    fun <T, R> Iterable<T>.pmap(
        exec: ExecutorService,
        transform: (T) -> R
    ): List<R>
    which uses an instance of ExecutorService to do all the transformations in parallel. An implementation of this is given e.g. here: https://stackoverflow.com/questions/34697828/parallel-operations-on-kotlin-collections/35638609#35638609 The problem is that I want to continue to work on the Rs as soon as they’re done, so List<R> is the wrong collection class (because a list will not be returned until all transformations are done). First I was thinking Sequence<R> would be the anwser for this. But now I think it isn’t. Firstly I could even make it work because I can’t simply modify to code to return a Sequence<R):
    = sequence{
        ....
        for (item in this) {
            exec.submit { yield transform(item) }
        }
        ....
    }
    is actually a compile-time error because I can’t call yield from a “sub-lambda”). But also a Sequence is supposed to be lazy, so you don’t start computing the next value until it’s requested. So what is the correct collection-like class?? Is this what coroutines’
    Flow
    is for? I guess I could also use a Java
    Stream
    , but that just seams so unidiomatic. UPDATE: So I tried the flow-builder but it runs into the same problem as with Sequence:
    fun <T, R> pFlowMap(
        items: Iterable<T>,
        exec: ExecutorService,
        transform: (T) -> R): Flow<R> = flow {
    
        for (item in items) {
            exec.submit { emit(transform(item)) }
        }
    
        exec.shutdown()
        exec.awaitTermination(1, TimeUnit.DAYS)
    }
    The
    emit
    is flagged with “Suspension functions can be called only within coroutine body”. So I tried wrapping that into a `runBlocking`:
    runBlocking {
            for (item in items) {
                exec.submit { emit(transform(item)) }
            }
        }
    but that dosn’t change a thing.
    d
    d
    g
    • 4
    • 13
  • a

    aerb

    11/04/2019, 1:23 PM
    Is there a good interop model where you can subscribe to Rx2 Observable & then unsubscribe when the scope is cancelled?
    d
    a
    z
    • 4
    • 4
Powered by Linen
Title
a

aerb

11/04/2019, 1:23 PM
Is there a good interop model where you can subscribe to Rx2 Observable & then unsubscribe when the scope is cancelled?
d

Dominaezzz

11/04/2019, 1:37 PM
Have you looked at
Flow
?
a

Adam Powell

11/04/2019, 1:42 PM
More specifically the Rx extensions that give you
Observable.asFlow()
z

Zach Klippenstein (he/him) [MOD]

11/04/2019, 5:14 PM
You can do
observable.asFlow().collect { }
or
observable.openSubscription().consumeEach { }
, but the former is potentially more efficient
a

aerb

11/05/2019, 12:55 AM
:thank:
View count: 3