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
  • m

    myanmarking

    06/03/2020, 11:44 AM
    I need advice on something:
    sealed class Updates{
        data class LiveUpdate(val progress: Int): Updates()
        data class History(val list: List<Int>): Updates()
    }
    
    private fun fetchUpdates(): Flow<Updates> {
        TODO()
    }
    
    private fun save(list: List<Updates.History>){
        TODO()
    }
    
    fun dispatchUpdates(): Flow<Updates.LiveUpdate>{
        val history = mutableListOf<Updates.History>()
        return fetchUpdates()
            .onEach { 
                if(it is Updates.History){
                    history.add(it)
                }
            }
            .onCompletion { if(it != null) save(history) }
            .filterIsInstance<Updates.History>()
    }
    Is there any way to improve this code so that the save part doesn't end up a side-effect? Something like an inner flow. I'm not sure how to approach this
    g
    a
    • 3
    • 22
  • j

    Jonathan Mew

    06/03/2020, 2:46 PM
    We have some HTTP requests which we are currently running consecutively but it's taking too long, so we would like to parallelise them. We would need to halt execution until they are all complete, and propagate an exception if any failed (wouldn't matter which exception was thrown if multiple requests fail). We don't need to capture any response data. What would be the neatest/most idiomatic way to achieve this?
    s
    • 2
    • 10
  • i

    Ivan Pavlov

    06/03/2020, 5:36 PM
    Hey guys. At the moment I'm processing events in the following way:
    val channel = BroadcastChannel<Event>(10)
    val receiveChannel = channel.openSubscription()
    val flow = receiveChannel.consumeAsFlow()
    
    flow.onEach(someProcessor::doOnEach)
        .catch { log.error(it) { "Error while processing event" } }
        .launchIn(coroutineScope)
    In my case I have to just skip an event if an exception is thrown in
    someProcessor.doOnEach(event: Event)
    and continue processing of next events. I can achieve what I want with
    flow.onEach {
      try {
        someProcessor.doOnEach(it)
      } catch (e: Throwable) {
         //log
      }
    }
    but I feel like I'm missing something. Is there a better way to do this?
    o
    d
    • 3
    • 4
  • e

    Eric Ampire [MOD]

    06/03/2020, 6:36 PM
    Can someone explain me why the compiler has executed the line 24 before starting the coroutine at the line 18 ?
    Enregistrement de l’écran 2020-06-03 à 20.30.14.mov
    o
    • 2
    • 2
  • v

    vaskir

    06/04/2020, 9:09 AM
    hi! Is there an existing suspend memoize function? If not, is the following code idiomatic?
    fun <T> (suspend () -> T).memoize() : suspend () -> T {
        var value: T? = null
        return suspend { value ?: this().also { value = it }}
    }
    
    suspend fun work() : Int = coroutineScope {
        delay(1000)
        22
    }
    
    val memoizedWork = ::work.memoize()
    e
    g
    +2
    • 5
    • 10
  • v

    vaskir

    06/04/2020, 1:29 PM
    Another question 🙂 Why is this warning? As I understand, it's the recommended way to wrap IO-bound blocking calls with
    <http://Dispatchers.IO|Dispatchers.IO>
    p
    s
    m
    • 4
    • 27
  • r

    rkeazor

    06/04/2020, 2:55 PM
    Can StateFlow represent one off events?
    🇳🇴 1
    z
    s
    • 3
    • 4
  • c

    clhols

    06/04/2020, 3:58 PM
    Have an Android app that launches the following coroutine when the app goes in the background (all activities are stopped):
    sessionTimeOutJob = GlobalScope.launch {
      delay(5.minutes)
      activity.finishAffinity()
    }
    So after 5 minutes the coroutine should resume and call finishAffinity(). But it doesn't happen on release builds. Only on debug builds. On release builds it first resumes when the app is selected in the Recents menu. Long past the 5 minute mark. Is it somehow the app lifecycle that prevents the coroutine from resuming?
    a
    • 2
    • 2
  • v

    vaskir

    06/04/2020, 4:06 PM
    if
    p
    is
    Deferred
    , then I expected it to be cancelled on timeout:
    select<Unit> {
        p.onAwait { println("ok") }
        onTimeout(1000) { println("timed out!") }
    }
    but it's not, it prints "timeout out!",
    p
    is not cancelled. What is the best way to cancel a
    Deferred
    by timeout?
    z
    • 2
    • 6
  • z

    Zach Klippenstein (he/him) [MOD]

    06/04/2020, 4:51 PM
    Has anyone ran into use cases for overloads of
    Flow
    operators for
    StateFlow
    that preserve the
    value
    property? I filed an issue for
    map
    here, curious if people have other use cases or use cases for other operators (or opinions about this proposal). https://github.com/Kotlin/kotlinx.coroutines/issues/2081
    s
    b
    • 3
    • 13
  • t

    Tash

    06/04/2020, 11:01 PM
    Hi everyone, curious about everyone’s preferred nomenclature for methods returning
    Flow<T>
    For example:
    // For Flow<List<*>>
    fun postsFlow(): Flow<List<Post>> 
    // OR
    fun postLists(): Flow<List<Post>>
    
    
    // For Flow<*>
    fun eventFlow(): Flow<Event>
    // OR
    fun events(): Flow<Event>
    Would be interesting to know if there are other preferred styles.
    👀 1
    r
    h
    +3
    • 6
    • 9
  • r

    Rick

    06/05/2020, 11:10 AM
    Hi need some help, i got error for the suspend function
    transactionAwait
    : "suspend function can be called only within coroutine body".
    callRealmSuspend { realm ->
                realm.transactionAwait {
                    realm.delete(RegionRealmObject::class.java)
                    realm.delete(ServiceRealmObject::class.java)
                }
            }
    and my
    callRealmSuspend
    function looks like this:
    suspend fun callRealmSuspend(call: (realm: Realm) -> Unit): Realm? {
        var realm: Realm? = null
    
        try {
            realm = Realm.getDefaultInstance()
            call(realm)
        }  catch (error: java.lang.Exception) {
            LogHelper.e(messages = *arrayOf("Unhandled error occurred: ${error.localizedMessage}."))
        }
    
        return realm
    }
    so how do I change
    callRealmSuspend
    function to fix the error/ provide a coroutine body? thanks!
    t
    s
    • 3
    • 4
  • d

    dpux

    06/05/2020, 5:07 PM
    Hi all! I am learning Flow, and was trying to understand how a flow can consume other flows in parallel and what happens in error scenarios. Here’s a test that I can’t get to work (requirements are documented in the
    handler
    function): https://pl.kotl.in/zyHCNXVLg
    e
    • 2
    • 10
  • v

    vaskir

    06/05/2020, 6:47 PM
    Why cancelling
    channelFlow
    does not cancel the child?
    suspend fun run() = channelFlow {
        suspendCancellableCoroutine<Unit> { cont ->
            cont.invokeOnCancellation { println("Cancelled.") }
            cont.resume(Unit) { }
        }
    
        for (x in 1..10) {
            send(x)
        }
    }
    
    suspend fun main(): Unit = coroutineScope {
        withTimeout(1000) {
            run().collect {
                println(it)
                delay(2000)
            }
        }
    }
    It produces:
    1
    Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms
    	at kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:158)
    	at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:128)
    	at kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.common.kt:497)
    	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:274)
    	at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)
    	at java.base/java.lang.Thread.run(Thread.java:834)
    
    Process finished with exit code 1
    s
    o
    +2
    • 5
    • 43
  • m

    Martin Nordholts

    06/05/2020, 7:20 PM
    Hi, I get Inappropriate blocking method call (
    BlockingMethodInNonBlockingContext
    ) on the
    exec()
    call in this code, but this is a false positive, right? Since I run with
    <http://Dispatchers.IO|Dispatchers.IO>
    I don’t see how the code would be problematic:
    suspend fun String.test() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        Runtime.getRuntime().exec(this@test)
    }
    o
    • 2
    • 1
  • d

    droidrcc

    06/06/2020, 9:57 PM
    I’m looking for an alternative to flow.emit(). I would need of a data structure (a sized circular buffered list) that would be “coroutine-safe” and the “put” operation is not blocking. The producer should not depend on the consumer and, it should be able to emit data even if there are no consumers listening. I was thinking to Channels, but they offers non-suspending send() only when declared Channel.UNLIMITED. Do you have any suggestion?
    o
    z
    • 3
    • 11
  • r

    rt

    06/07/2020, 7:13 AM
    Hi. How do I figure out that the downstream is exhausted (completed/whatever the right terminology is) in a flow builder? This is the code I currently have: https://pl.kotl.in/tCjm9ICUp - it will time out because my loop condition is obviously not working. In general, what I'm trying to do is have this
    while (...) { delay(1000); emit(buffer); buffer.clear() }
    to have timed buffering. I'm aware there are operators for this, just trying to figure things out for myself. Also, any other notes on pitfalls of my implementation would be appreciated.
    f
    z
    • 3
    • 18
  • m

    Martin Nordholts

    06/08/2020, 6:46 AM
    Hi, What is the idiomatic way to make suspend functions cross Java callback boundaries? This code
    suspend fun g(): String = "bar"
    suspend fun f(mutableMap: MutableMap<String, String>) {
        mutableMap.computeIfAbsent("foo") {
            g()
        }
    }
    gives me
    Suspension functions can be called only within coroutine body
    compilation errror on the
    g()
    call. The only solution I can come up with is to re-implement
    computeIfAbsent
    in Kotlin and make the
    fun
    inline
    , but that does not seem like an elegant, idiomatic solution. What is the proper solution to this problem?
    o
    d
    e
    • 4
    • 15
  • e

    elizarov

    06/08/2020, 9:08 AM
    📣 Shootout to all Android devs using MVI, MVVM, etc with coroutines. How do you handle events that need to be processed exactly once by your views (like navigation events, etc)? That is, what approach do you use with coroutines to work around the problem explained here for LiveData: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 0️⃣ I’m avoiding this problem altogether, not using anything like
    Rx/Channel/Flow/LiveData
    to deliver those events (comment in :thread-please: what you do instead). 1️⃣ Using an
    Event
    wrapper class, adapting solution in the above story to coroutines. 2️⃣ Using a [buffered or rendezvous]
    Channel
    for events, exposing it to the views either as
    Channel
    or as a
    Flow
    via
    receiveAsFlow()
    extension. 3️⃣ Some other approach (comment in :thread-please:).
    0️⃣ 7
    2️⃣ 27
    3️⃣ 3
    1️⃣ 26
    g
    m
    +12
    • 15
    • 26
  • e

    elizarov

    06/08/2020, 12:29 PM
    📣 For all of you who picked 2️⃣ (using
    Channel
    ) how do you work around the fact that
    Channel.receive
    can get a message in an activity that is already destroyed and thus attempt to work with it will cause an
    IllegalStateException
    ? (see this demo https://pl.kotl.in/Rs18kihuJ) The same problem happens when you use
    Channel.receiveAsFlow
    and then collect from the flow (see this demo https://pl.kotl.in/-ehZrPMl4). 😱 I never knew it could happen! All my code is broken! 👍 It never happens to me because I use
    immediate
    dispatcher (Android provides that by default) and I always post from the main thread, so between the event is posted and is being processed my activities cannot get destroyed. 👉 I do something else (comment in :thread-please:)
    😱 3
    👍 7
    👉 4
    s
    b
    +4
    • 7
    • 32
  • d

    dewildte

    06/08/2020, 12:48 PM
    @elizarov What is the motivation behind these two polls? What are the answers going to be used for?
    e
    • 2
    • 7
  • k

    ken_kentan

    06/09/2020, 1:34 AM
    Hi, I got warning
    Inappropriate blocking method call
    when call blocking method in suspend function. I don't know that why this code was warned... How to fix this?
    import java.net.URL
    
    suspend fun foo(bar: String): String {
        if (bar.isEmpty()) {
            return ""
        }
        return withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            // warning: Inappropriate blocking method call
            URL("<https://www.example.com>")
                .readText()
        }
    }
    o
    e
    +2
    • 5
    • 13
  • r

    rkeazor

    06/09/2020, 7:57 AM
    Hey Flow.zip works with hot flows correct?
    e
    • 2
    • 4
  • k

    ken_kentan

    06/09/2020, 9:00 AM
    I'm planning to call method in suspend function that will throw IOException. In this case, IDE warn it as
    Inappropriate blocking method call
    . So, Should not I call method(will throw IOE) in suspend function?
    suspend fun foo() {
        // warning: Inappropriate blocking method call
        throwIoException()
    
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            // warning: Inappropriate blocking method call
            throwIoException()
        }
    }
    
    @Throws(IOException::class)
    fun throwIoException() {
        // something blocking process
    }
    o
    e
    • 3
    • 9
  • s

    sdeleuze

    06/09/2020, 5:16 PM
    Hey, I try to use Kotlin
    1.4-M2
    and related
    1.3.7-1.4-M2
    Coroutines dependencies with Gradle 6.5 and get this error:
    > Could not resolve all files for configuration ':kotlin-coroutines:kotlinCompilerPluginClasspath'.
       > Could not resolve org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1.
         Required by:
             project :kotlin-coroutines > org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.4-M2 > org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.4-M2
             project :kotlin-coroutines > org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.4-M2 > org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.4-M2 > org.jetbrains.kotlin:kotlin-scripting-common:1.4-M2
          > Cannot choose between the following variants of org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7-1.4-M2:
              - iosArm32-api
              - iosArm32-iosArm32MetadataElements
              - iosArm64-api
              - ...
      All of them match the consumer attributes:
              - Variant 'iosArm32-api' capability org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7-1.4-M2:
                  - Unmatched attributes:
                      - Provides org.gradle.status 'release' but the consumer didn't ask for it
                      - Provides org.gradle.usage 'kotlin-api' but the consumer didn't ask for it
                      - Provides org.jetbrains.kotlin.native.target 'ios_arm32' but the consumer didn't ask for it
                      - Provides org.jetbrains.kotlin.platform.type 'native' but the consumer didn't ask for it
              - ...
    Any hint about how to fix this (worked fine with Kotlin
    1.3.72
    and Coroutines
    1.3.5
    )?
    l
    • 2
    • 3
  • k

    Kris Wong

    06/09/2020, 8:19 PM
    I am using
    runBlocking(someContext)
    , and within the block a call is made to a method that is calling
    launch
    using a scope that was created with the same context. however, it is not blocking. am I doing something wrong?
    o
    s
    • 3
    • 10
  • c

    colintheshots

    06/09/2020, 8:48 PM
    If I cancel an entire coroutineScope, will launches still be accepted with the same scope? I'm trying to resolve a debate.
    o
    • 2
    • 9
  • l

    Luis Munoz

    06/09/2020, 9:17 PM
    In this code will the fist collect finish before the second collect is started or is possible that the execution will interleave?
    val singleThread =   newSingleThreadContext("SingleThread")
    val flow = flow { 
     emit("a")
     blocking call
     delay(1000)
     emit("b")
    }.flowOn(singleThread)
    
    launch(<http://Dispachers.IO|Dispachers.IO>) {
        flow.collect {
            println(it)
        }
    }
    launch(<http://Dispachers.IO|Dispachers.IO>)  { 
        flow.collect {
                println(it)
        }
    }
    o
    r
    • 3
    • 20
  • g

    groostav

    06/10/2020, 11:04 PM
    will the return value from
    scope.actor<>{}
    always implement
    Job
    ? I want to implement some code that calls
    actor.close()
    , and then just to keep things synchronous I want to call
    (actor as Job).join()
    , will that work in future kotlinx-coroutines?
    o
    • 2
    • 1
  • r

    Ryan Simon

    06/11/2020, 12:51 AM
    hey all, curious if any of you might be able to help me solve a StateFlow/Channel predicament. i've got a
    StateFlow<State>
    setup to track state changes of a screen in Android. these state changes are observed by the
    View
    . additionally, i use a
    Channel<Intent>
    to
    offer
    some
    Intent
    from the
    View
    to the
    ViewModel
    . the problem is that my code will suspend and it feels like the main thread is blocked until an
    Intent
    is fully processed by the
    ViewModel
    . i've added some of my code below to hopefully help with understanding the problem
    // ViewModel
    
        val intentChannel = Channel<Intent>(Channel.UNLIMITED)
        private val _state = MutableStateFlow<State>(Idle)
        val state: StateFlow<State>
            get() = _state
    
        init {
            viewModelScope.launch {
                handleIntents()
            }
        }
    
        // TODO: we seem to suspend the main thread every time we process an intent; NOT GOOD!
        private suspend fun handleIntents() {
            intentChannel.consumeAsFlow().collect {
                when (it) {
                    is Init -> with(it) {
                        // do something on initialization
                    }
                    is Load -> with(it) {
                        _state.value = Loading(page == 0)
                        getBrandProducts(page = page)
                    }
                    is Sort -> with(it) {
                        _state.value = Sorting
                        getBrandProducts(page = 0)
                    }
                }
            }
        }
    
        // brandRepository flows on a <http://Dispatcher.IO|Dispatcher.IO>
        private suspend fun getBrandProducts(page: Int) {
            brandRepository.getPromotedProducts(
                categorySlug = categorySlug,
                sortBy = currentSortBy,
                sortOrder = currentSortOrder,
                offset = page * requestLimit,
                limit = requestLimit
            )
                .map { result -> result.getOrNull()!! }
                .collect { result -> _state.value = Loaded(result) }
        }
    😒uspend: 1
    ☘️ 1
    z
    • 2
    • 33
Powered by Linen
Title
r

Ryan Simon

06/11/2020, 12:51 AM
hey all, curious if any of you might be able to help me solve a StateFlow/Channel predicament. i've got a
StateFlow<State>
setup to track state changes of a screen in Android. these state changes are observed by the
View
. additionally, i use a
Channel<Intent>
to
offer
some
Intent
from the
View
to the
ViewModel
. the problem is that my code will suspend and it feels like the main thread is blocked until an
Intent
is fully processed by the
ViewModel
. i've added some of my code below to hopefully help with understanding the problem
// ViewModel

    val intentChannel = Channel<Intent>(Channel.UNLIMITED)
    private val _state = MutableStateFlow<State>(Idle)
    val state: StateFlow<State>
        get() = _state

    init {
        viewModelScope.launch {
            handleIntents()
        }
    }

    // TODO: we seem to suspend the main thread every time we process an intent; NOT GOOD!
    private suspend fun handleIntents() {
        intentChannel.consumeAsFlow().collect {
            when (it) {
                is Init -> with(it) {
                    // do something on initialization
                }
                is Load -> with(it) {
                    _state.value = Loading(page == 0)
                    getBrandProducts(page = page)
                }
                is Sort -> with(it) {
                    _state.value = Sorting
                    getBrandProducts(page = 0)
                }
            }
        }
    }

    // brandRepository flows on a <http://Dispatcher.IO|Dispatcher.IO>
    private suspend fun getBrandProducts(page: Int) {
        brandRepository.getPromotedProducts(
            categorySlug = categorySlug,
            sortBy = currentSortBy,
            sortOrder = currentSortOrder,
            offset = page * requestLimit,
            limit = requestLimit
        )
            .map { result -> result.getOrNull()!! }
            .collect { result -> _state.value = Loaded(result) }
    }
😒uspend: 1
☘️ 1
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 12:53 AM
my code will suspend and block the main thread
“suspend” and “block” mean different things. Blocking the main thread is (generally) bad. Suspending a coroutine that’s running on the main thread is perfectly fine.
r

Ryan Simon

06/11/2020, 12:53 AM
the effect i see as a user is that when we go to load the next page of results by sending a
Load
intent with a new page, the main thread hangs as the user scrolls and delays the scrolling animation until the work is done
@Zach Klippenstein (he/him) [MOD] for sure, i guess what i mean is that it feels like the main thread is being blocked
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 12:56 AM
Hm, nothing in this code looks like it actually blocks. You’re sure
getPromotedProducts
isn’t the culprit?
Have you attached a debugger or added any trace statements to see where the block is occurring?
r

Ryan Simon

06/11/2020, 12:57 AM
fun getPromotedProducts(
        categorySlug: String,
        sortBy: String?,
        sortOrder: String?,
        offset: Int,
        limit: Int
    ): Flow<Either<List<BrandProduct>>> {
        // TODO need to solve for retry/error handling for Retrofit
        return flow {
            val userLocation = locationRepository.getLocation().receive().getOrNull()

            try {
                val result = userLocation?.run {
                    api.getPromotedProducts(
                            categorySlug = categorySlug,
                            latlng = "${this.latitude},${this.longitude}",
                            sortBy = sortBy,
                            sortOrder = sortOrder,
                            offset = offset,
                            limit = limit
                    ).run { success(this.data?.brandProducts!!) }
                } ?: Either.error<List<BrandProduct>>(ServerError)

                emit(result)
            } catch (e: Exception) {
                when (e) {
                    is HttpException -> {
                        Timber.d("HttpError ${e.response()?.errorBody()?.string()}")
                    }
                }

                emit(Either.error(ServerError))
            }
        }.flowOn(dispatcher)
    }
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 12:57 AM
As an aside,
consumeAsFlow().collect
is unnecessary, you can just do
consumeEach
.
👍 1
r

Ryan Simon

06/11/2020, 12:57 AM
the dispatcher used here is
<http://Dispatchers.IO|Dispatchers.IO>
@Zach Klippenstein (he/him) [MOD] i did a little debugging, and it looks like we are waiting for the getPromotedProducts call to finish. thing is that it doesn't seem to be doing anything blocking
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:04 AM
dispatcher
here is
<http://Dispatchers.IO|Dispatchers.IO>
? (in the future, big code posts like this are generally easier to read when posted as snippets instead of inline)
r

Ryan Simon

06/11/2020, 1:04 AM
sorry about that, yes it’s a
<http://Dispatchers.IO|Dispatchers.IO>
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:05 AM
So
getPromotedProducts
isn’t even returning immediately?
r

Ryan Simon

06/11/2020, 1:06 AM
it is returning immediately, but something around the collection of the flow causes this main thread hiccup
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:07 AM
Another aside, this also looks like it could just be a simple suspend function, since it only emits one thing.
💯 1
r

Ryan Simon

06/11/2020, 1:09 AM
yeah, this is more experimentation around making our repository layers return flows to make combining values and applying operators really seamless
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:10 AM
So if you change the state to
Loaded
while you’re scrolling, and
Loaded
doesn’t include any items, does your RecyclerView keep its current list until it gets a new one from a
Loaded
state?
r

Ryan Simon

06/11/2020, 1:12 AM
no, it currently throws everything out regardless of the number of items
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:13 AM
So when you start loading you clear your RecyclerView?
r

Ryan Simon

06/11/2020, 1:14 AM
no only once Loaded state is read from the Activity
are you thinking it’s more of an issue with my Activity/View logic? i was leaning that way because the coroutine stuff all seems to check out
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:16 AM
I’m not sure, but I don’t see anything in this code that looks like it would affect your scrolling like you’ve described.
Just to verify, if you remove the
_state.value = Loading(page == 0)
line, does that change anything?
r

Ryan Simon

06/11/2020, 1:17 AM
it doesn’t, just doesn’t show my progress bar. that was one of the first things i tried haha
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:18 AM
Can you debug more and try to find out exactly what line is blocking? Also maybe try putting a
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
around your entire
getBrandProducts
method body?
r

Ryan Simon

06/11/2020, 1:19 AM
yeah for sure, i’ll be able to mess more with it tomorrow. thanks for the ideas, and walking through it with me. much appreciated! i’ll post back tomorrow when i’ve got an update
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 1:27 AM
You could also use the Android Studio profiler to see which thread is being blocked and what the stack traces are during that blockage
Good luck!
r

Ryan Simon

06/11/2020, 1:29 AM
Good idea, thank you!
@Matt Rea 👋
@Zach Klippenstein (he/him) [MOD] hey Zach, so i finally got some time to look at this problem more, and now I'm pretty darn sure that it has nothing to do with coroutines, and everything to do with Android itself i've include some videos below. one video has had an added
delay(1000)
to the network request
Flow
we make to fetch items, and the other video has no
delay
the video with no
delay
has the very obvious frame drops, and the one with a
delay(1000)
doesn't
without-delay.webmwith-delay.webm
my intuition points to a potential issue in where we are scrolling and loading content into the recycler adapter so fast, that we drop frames because the system can't handle that load within the 16ms window we have to draw everything
investigating more, but thought i owed you an update
View count: 4