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/19/2019, 1:05 PM
    If I'm using retrofit 2.6.0 and using the suspend fun do I have to also add the CoroutineCallAdapterFactory when creating the retrofit object?
    🇳🇴 1
    j
    • 2
    • 1
  • j

    Joan Colmenero

    10/19/2019, 4:07 PM
    Hello I'm moving to the new version of retrofit and I was using a convertor that was creating a
    ResultWrapperT
    from
    CallT
    but now reading this answer [1] from stackoverflow then I realized that if I'm using
    suspended fun
    I do not have to add the
    CallT
    so, how do I do the change now? I was using this method :
    fun <reified T:Any> execute(function: () -> Call<T>): ResultWrapperT =
            try {
                when (T::class) {
                    Unit::class -> function().execute().let {
                        ResultWrapper.Success(Unit as T)
                    }
                    else -> function().execute().body()?.let {
                        ResultWrapper.Success(it)
                    } ?: ResultWrapper.Error(Exception("no body there"))
                }
            } catch (e: Exception) {
                ResultWrapper.Exception(e)
            }
    Any idea? The problem now is that as it's not a
    CallT
    I do not have the
    execute()
    method... [1] : https://stackoverflow.com/a/57810074/4329781
    k
    • 2
    • 11
  • p

    poohbar

    10/19/2019, 8:30 PM
    Sequences supply data on demand but in this case the producer is pushing the data. So I guess I might need a channel? 🤔
    a
    j
    • 3
    • 2
  • m

    Mani

    10/20/2019, 9:12 AM
    Folks, I am writing my first coroutine. In the follow piece of code, I am fetching a bunch of objects and then doing a IO call with other service. Need some feedback whether my understanding of coroutine is correct.
    val allWarehouses: List<Warehouse> = getWarehouses()
    
     GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            allWarehouses.forEach { warehouse ->
            	val notes = getNotes()
    			// I want to run this loop in parallel
    			notes.forEach {
    			   serviceClient.markDone(note)  // this is an IO call 
    			}
            }
    }
    I want to run the forEach operation in parallel. Is this the right way of doing?
    a
    g
    • 3
    • 8
  • m

    Mani

    10/20/2019, 9:23 AM
    For parallel execution, is this the right way
    notes.parallelStream().forEach { println(it) }
    p
    • 2
    • 1
  • t

    tapac

    10/20/2019, 6:47 PM
    Is there any simple way to implement
    Deferred
    interface? I was trying to delegate that interface to an instance returned by
    async
    function, but it doesn't work well.
    class MyDeferred<T>(val original: Deferred<T>) : Deferred<T> by original
    
    MyDeferred(async{ ...} )
    I want to be able to call some code on async completition or execption, maybe there is another way?
    a
    o
    d
    • 4
    • 13
  • j

    Jayden

    10/21/2019, 4:28 AM
    How might I create a flow of a sealed class? I have something like this:
    val events =
      flowOf(
          callbackFlow { }.map { SealedClass.Property1 },
          callbackFlow { }.map { SealedClass.Property2 },
          BroadcastChannel(1) .asFlow().map { SealedClass.Property3 }
    ).flattenMerge()
    But, when I
    offer
    to the broadcast channel nothing is emitted from events. The callback flows however, work fine.
    d
    • 2
    • 3
  • r

    Robert Jaros

    10/21/2019, 7:40 AM
    Which is better?:
    .flow().map { ... }.toList()
    or
    .flow().toList().map { ... }
    o
    v
    +3
    • 6
    • 5
  • l

    Lewon.G

    10/21/2019, 12:39 PM
    How can I return the String "newURL" with coroutines ? fun firstServerRequest(): String? { val service = pokemonNetwork.service service.getAllPokemonDatas(50,0).enqueue(object : Callback<PokemonList> { override fun onFailure(call: Call<PokemonList>, t: Throwable) { } override fun onResponse(call: Call<PokemonList>, response: Response<PokemonList>) { response.body()?.results?.forEach { pokemon -> var newURL = pokemon.url } } }) return newURL }
    e
    • 2
    • 2
  • m

    Matt Thiffault

    10/21/2019, 7:55 PM
    Is there a way to use select (or some other similar mechanism) to select for messages on an arbitrary set of Channels not known at compile time (provided the channels have the same message type)?
    o
    b
    • 3
    • 8
  • j

    Jan Skrasek

    10/22/2019, 12:25 PM
    Let's have a channel (ConflatedBroadcastChannel) wired in a model. What is an alternative to
    SingleLiveData<T>
    , e.g. something what observe value just once, but on multiple places (observers).
    t
    m
    • 3
    • 5
  • s

    stkent

    10/22/2019, 2:15 PM
    Cross-posting from #android: https://kotlinlang.slack.com/archives/C0B8M7BUY/p1571753686276700
    s
    • 2
    • 4
  • l

    Luke Rohde

    10/22/2019, 2:19 PM
    is there a recommended way to schedule a periodic task with coroutines? i see
    ticker
    , but it’s marked as obsolete and it’s unclear why
    m
    w
    +3
    • 6
    • 6
  • d

    davide

    10/22/2019, 3:04 PM
    Hi all, I'm playing with Flow and error handling. I'm doing somethink like: (1..5).asFlow().onEach{ //throw error }.retryWhen { c, a -> ... } But the flow restarts from the beginning. What is the best way to skip the emitted element that cause the error and restart from the next one?
    s
    • 2
    • 5
  • k

    kevinherron

    10/22/2019, 5:33 PM
    I’m seeing some pretty disappointing CPU usage from a low throughput coroutines workload (sending ~40-50 network requests per second) that is all non-blocking I/O, barely any CPU work. Using the async profiler shows the DefaultDispatcher threads are spending the majority of their time in the coroutines scheduler (mostly in
    Worker.doPark
    or
    WorkQueue.trySteal
    . Is this… expected?
    l
    m
    v
    • 4
    • 13
  • n

    Nikky

    10/22/2019, 8:52 PM
    guess this is coroutine related.. why can i not do
    suspend operator get(id: String)
    and is there any way to use operator overloading with suspending functions ?
    l
    i
    +3
    • 6
    • 7
  • n

    napperley

    10/23/2019, 1:19 AM
    Does the KotlinX Coroutines project ( https://github.com/Kotlin/kotlinx.coroutines ) accept PR's for adding a new scheduler?
    g
    • 2
    • 1
  • j

    james

    10/23/2019, 2:22 AM
    can anyone point me in the right direction on a strategy for how I might use Flow's
    debounce
    to debounce text changes from an Android EditText? I've done this previously using RxJava but RxAndroid did the hard work there with
    RxTextView.textChanges
    .. I'm wondering how I can achieve this in the world of coroutines/flow
    g
    m
    • 3
    • 3
  • t

    Tuan Kiet

    10/23/2019, 8:32 AM
    in
    suspendCancellableCoroutine { continuation ->
    do we need to check anything like
    isActive or isCancelled
    before call
    resumeWith
    and why?
    d
    v
    • 3
    • 4
  • k

    Kulwinder Singh

    10/23/2019, 12:43 PM
    Hi, is it good to use multiple
    combine
    in flows like below
    Firestore.getFlow1().combine(Firestore.getFlow2()) { f1, f2 -> Result(f1,f2)}
                    .combine(Firestore.getFlow3()) { f3, result -> result.f3 = f3 }
                    .collect { _liveData.value = it}
    Here
    Firesstore.get*
    all are wrappers that converts firestores snapshow listeners to flow, so here i have to listen three flows and want to combine them . is it good to do like this or there is any other way also ?
    l
    p
    • 3
    • 5
  • z

    zak.taccardi

    10/23/2019, 3:45 PM
    How does OkHttp compare to Ktor Client? Seems they land on similar use cases? Why might I prefer one over the other?
    f
    c
    • 3
    • 6
  • s

    sdeleuze

    10/24/2019, 12:11 PM
    What is the recommanded what to turn Javascript callback based API like
    EventSource
    to a
    Flow
    that emits the data received by the
    onmessage
    callback ?
    v
    • 2
    • 19
  • a

    Animesh Sahu

    10/24/2019, 4:07 PM
    any database driver implementation with coroutines?
    l
    c
    b
    • 4
    • 6
  • z

    zak.taccardi

    10/24/2019, 5:46 PM
    Let’s say I have a
    CoroutineScope
    backed by a multi-thread dispatcher. I also have a
    Channel<Int>
    that needs to receive incoming messages.
    val scope = CoroutineScope(Dispatchers.Default)
    val channel: Channel<Int> = TODO()
    
    fun onNewInt launch`(newInt: Int) {
      // `newInt` is delivered from outside a coroutine
      // what is the appropriate way to emit to the channel? 
    }
    I see two possibilities (see code snippet)
    Untitled.kt
    2️⃣ 1
    1️⃣ 2
    w
    o
    g
    • 4
    • 6
  • z

    zak.taccardi

    10/24/2019, 10:21 PM
    What would be the idiomatic way to emit a
    Flow<Unit>
    every 40 milliseconds? old solution:
    channelFlow<Unit> {
      while (isActive) {
        delay(40)
        send(Unit)
      }
    }
    new, better solution:
    flow {
        while (true) {
            delay(40)
            emit(Unit)
        }
    }
    f
    d
    +3
    • 6
    • 15
  • j

    james

    10/25/2019, 4:48 AM
    can someone point me to some information on calling a
    suspend fun
    from a java class with Java 7 compatibility? I found some information by googling on how to do this with Java 8+, but not Java 7
    g
    s
    d
    • 4
    • 9
  • u

    ubu

    10/25/2019, 11:30 AM
    Hi there. I couldn’t get why this code was being run on the main thread (why wouldn’t suspend function create its own thread):
    override suspend fun createAccount(
            name: String,
            avatarPath: String?
        ) : AccountEntity {
    
            Timber.d("Thread: ${Thread.currentThread().name}")
    
            return service.createAccount(name, avatarPath).let { response ->
                AccountEntity(
                    id = response.id,
                    name = response.name,
                    avatar = response.avatar.toEntity()
                )
            }
        }
    I launch inside
    ViewModelScope
    . Any help will be appreciated!
    d
    l
    g
    • 4
    • 8
  • z

    zak.taccardi

    10/25/2019, 8:21 PM
    Why is
    viewModelScope
    being pushed by the Android team? It requires a bunch of workarounds that would be completely unnecessary if the
    CoroutineScope
    was just injected into the
    ViewModel
    p
    d
    +6
    • 9
    • 153
  • f

    Fudge

    10/26/2019, 4:15 PM
    what is the best dispatcher to use for user input?
    z
    c
    g
    • 4
    • 19
  • a

    Adriano Celentano

    10/27/2019, 12:28 PM
    can i launch a new coroutine inside a suspending function with the same scope the suspending function was called ? sth like this
    suspend fun test() {
       suspendingFunctionScope.launch {
          ...
       }
    }
    f
    t
    • 3
    • 5
Powered by Linen
Title
a

Adriano Celentano

10/27/2019, 12:28 PM
can i launch a new coroutine inside a suspending function with the same scope the suspending function was called ? sth like this
suspend fun test() {
   suspendingFunctionScope.launch {
      ...
   }
}
f

Fudge

10/27/2019, 12:35 PM
You can make test an extension function on a coroutineContext
t

tseisel

10/27/2019, 12:36 PM
Yes, you can wrap your
launch
call into a
coroutineScope
block:
suspend fun test() = coroutineScope {
    launch {
        ...
    }
}
Note that the
test
function will not return before the launched coroutine is completed. If that's not what you want, you should consider making
test
a non-suspending extension of
CoroutineScope
, which is the usual way to define a function that starts a coroutine:
fun CoroutineScope.test()
a

Adriano Celentano

10/27/2019, 12:48 PM
is it possible to have this somehow object oriented like this ?
class GameEngine {
    fun CoroutineScope.start() {
...
}
t

tseisel

10/27/2019, 1:06 PM
You can do that, but it's not very handy. You would have to write something like this:
val engine = GameEngine()
with(engine) {
    scope.start()
}
This is because a member function can (normally) have only one receiver. Something like
fun startIn(scope: CoroutineScope)
would be better. You can also pass a
CoroutineScope
as a constructor parameter of your engine, provided the engine has the same lifetime as the passed scope.
a

Adriano Celentano

10/27/2019, 1:56 PM
thank you now its clear to me 👍
View count: 7