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

    julian

    07/02/2020, 2:13 AM
    Does Flow have something like RxJava's
    compose
    operator? (Rather than operating individual items emitted by a Flow, it would operate on the Flow itself, returning a new composed Flow.)
    o
    l
    • 3
    • 6
  • j

    Jamie Craane

    07/02/2020, 6:46 AM
    We are integrating flow in out Kotlin Native project to implement viewmodels in the common module so those viewmodels can be shared between iOS and Android. At the moment we have started using flow for this which seems to fit nicely in the overall architecture. A viewmodel can expose a flow to which the UI can collect to. The UI can also indicate it wants new data (refresh). I have implemented this in the following way, by using a MutableStateFlow indicating the refresh status. I have a simple example implementation ((with documentation)) below which seems to work quite well. Is this the correct approach to this problem with Kotlin flows?
    @ExperimentalCoroutinesApi
    class PersonsViewModel {
        private val realApi = RealApi()
    
        // cached list of persons
        private var cachedPersons: List<Person>? = null
    
        // indicates of the data should be retrieved from network or cache. This is a MutableStateFlow since its value
        // can be updated by the UI (for example uses refreshes the page).
        private val refreshTrigger: MutableStateFlow<RefreshTrigger> = MutableStateFlow(RefreshTrigger.FromCache())
    
        // flatMapLatest on refreshTrigger because we are interested in the latest value only.
        var persons: Flow<CommonDataContainer<List<Person>>> = refreshTrigger.flatMapLatest { trigger ->
            flow<CommonDataContainer<List<Person>>> {
                // Notify the UI we are loading data
                emit(CommonDataContainer.Loading())
                val refresh = trigger is RefreshTrigger.Refresh
                val cached = cachedPersons
                if (!refresh && cached != null) {
    //                Return the cached data if not explicitly refreshed and data is in cache.
                    emit(CommonDataContainer.Success(cached))
                } else {
                    // Refresh or data is not in cache, retrieve from network.
                    retrievePersonsFromNetwork()
                }
            }
        }
    
        private suspend fun FlowCollector<CommonDataContainer<List<Person>>>.retrievePersonsFromNetwork() {
            val response = realApi.retrievePersons()
            when (response) {
                is Success -> {
                    cachedPersons = response.data
                    // Emit the data.
                    emit(CommonDataContainer.Success(response.data))
                }
                // Something went wrong, emit a failure.
                is Failure -> emit(CommonDataContainer.Failure())
            }
        }
    
        suspend fun refresh() {
            yield()
            refreshTrigger.value = RefreshTrigger.Refresh()
        }
    }
    
    // CommonDataContainer can represent various states which are interesting to collectors.
    sealed class CommonDataContainer<out T> {
        // Indicates the data is loading
        class Loading<T> : CommonDataContainer<T>()
        // Indicates an error occurred retrieving the data
        class Failure<T> : CommonDataContainer<T>()
        // Indicates success. Holds the data in the data property.
        class Success<out T>(val data: T) : CommonDataContainer<T>()
    }
    
    // Indicates where the data should com from. Both classes  have a unique id to make sure the Refresh trigger is always emitted by MutableStateFlow
    // since MutableStateFLow does not emit the value if the new value is the same as the current value.
    sealed class RefreshTrigger {
        data class FromCache(private val id: String = Random.nextInt().toString()) : RefreshTrigger()
    
        /**
         * Every instance has a unique id so the refresh StateFlow sees it as a new value. StateFlow does not emit the same value twice if
         * the current value is the same as the new value.
         */
        data class Refresh(private val id: String = Random.nextInt().toString()) : RefreshTrigger()
    }
    i
    d
    • 3
    • 3
  • i

    ildar.i [Android]

    07/02/2020, 10:56 AM
    Got a question: - I have three
    suspend
    operations, each can be called independently:
    foo1(list)
    ,
    foo2(list)
    and
    foo3(list)
    - each function changes state of items in list -
    foo1
    just makes request to the server and returns updated list (updates 1 step) -
    foo2
    calls
    foo1
    and then with combined result makes a request (updates 2 steps) -
    foo3
    calls
    foo2
    , combines result and makes a request (updates 3 steps) Problem is,
    foo2
    needs to gather data (SMS-code) via DialogFragment. Is there a way to build a continuous pipeline, so the
    foo3
    can continue its flow after
    foo2
    called a dialog, gathered input and returned?
    e
    g
    • 3
    • 6
  • v

    vineethraj49

    07/02/2020, 2:01 PM
    what's a good way to do things concurrently in
    init {}
    ?
    d
    g
    +2
    • 5
    • 16
  • r

    Raul

    07/02/2020, 2:58 PM
    Quick question, is there any channel to share new articles we published recently? Don't want to create any spam here
    d
    • 2
    • 2
  • j

    jean

    07/03/2020, 6:50 AM
    I’m having issues in my unit test when I try to use AssertFlow extension on a StateFlow instance. If I use
    expectItem()
    I get a timeout exception, but if I check for no more items, it tells me something was received. Any hints to fix this?
    j
    • 2
    • 2
  • n

    Nemanja Scepanovic

    07/03/2020, 1:44 PM
    Hi guys, would you say it’s necessary or unnecessary to change the dispatcher upon flatMapLatest’s transform?
    fun getBooksFlow: Flow<List<Book>> = 
         getUserFlow().flatMapLatest { user -> getUserBooksFlow(user.userId) }.flowOn(Dispatchers.Default)
    g
    • 2
    • 1
  • m

    Marcin Wisniowski

    07/03/2020, 10:03 PM
    Hello, I have two `Channel`s, and I want to
    .receive()
    on both of them, so if there is anything in channel 1 or anything in channel 2 it resumes, but of course
    .receive()
    doesn't actually work since I can't call it on both. What should I be using here? The point here is that channel 1 is higher priority, so I want to get the next item, from channel 1 if there are any, and from channel 2 if channel 1 is empty.
    o
    • 2
    • 3
  • u

    ursus

    07/04/2020, 11:35 AM
    did I miss something? are there any gotchas?
    e
    • 2
    • 36
  • t

    Tim Malseed

    07/04/2020, 2:07 PM
    I’m using
    StateFlow
    to sort of cache and share the result of a coroutine. The
    StateFlow
    is held in a singleton, and accessed (collected) from multiple different places. When the scope that launches one of these collectors is cancelled (via
    scope.cancel()
    , it seems that the
    StateFlow
    is cancelled and no longer emits to any collectors. Can I cancel the collectors launched in a scope, without cancelling the parent producer?
    d
    l
    i
    • 4
    • 82
  • t

    tseisel

    07/05/2020, 12:32 PM
    What's the purpose of the
    Flow.cancellable
    operator ? What kind of use case does it solve ?
    l
    e
    o
    • 4
    • 10
  • m

    Michał Kalinowski

    07/05/2020, 3:02 PM
    Hey, is there any way to pass e.g coroutine scope from suspended function to normal function and then invoke another suspend function on this scope? For example:
    suspend fun fooA(){
      coroutineScope {
        fooB(this)
      }
    }
    
    fun fooB(coroutineScope: CoroutineScope){
      continueWithSuspend(coroutineScope){
        continueSuspendingFooA()
      }
    }
    
    private suspend fun continueSuspendingFooA(){}
    e
    a
    m
    • 4
    • 10
  • j

    Jamie Craane

    07/05/2020, 4:45 PM
    I have noticed the zip operator executes the coroutines sequentially, see the following example:
    flowOf(getWeather(loc)).zip(flowOf(reverseGeocode(loc))) { weather, address ->
                weather to address
            }
                .flowOn(Dispatchers.Default)
                .collect { println(it) }
    The time it takes to execute this is the total time of the getWeather and reverseGeocode calls combined. I know I can use a map operator and two async/wait blocks to execute the two calls asynchronously. Is it possible to execute multiple coroutines like this with flow operators? I tried a couple of different things but without success? I saw https://github.com/Kotlin/kotlinx.coroutines/issues/1147 so perhaps all operators are sequential for now.
    o
    m
    • 3
    • 3
  • d

    dimsuz

    07/05/2020, 9:04 PM
    I need to unit-test the code involving a
    scan
    operator and hot event stream. Basically I want to configure the flow, send events and verify they are received:
    runBlocking(Dispatchers.Default) {
        val events = BroadcastChannel<Int>(capacity = Channel.BUFFERED)
        launch {
          events.asFlow().scan(1) { accumulator, value -> value }
            .take(2)
            .collect { println("received $it") }
        }
        launch {
          events.send(42)
        }
      }
    The above doesn't work, it receives 1(inital accum) item and then hangs indefinitely, because
    send
    is done before collect begins. I tried moving
    send
    inside the
    collect
    , after initial element is received, but this doesn't work, because
    scan
    is implemented so that its internal
    collect
    also starts after my
    send
    is called (it starts after first collection completes). Any advice on how to do that?
    i
    • 2
    • 2
  • m

    Marcin Wisniowski

    07/05/2020, 10:06 PM
    I'm building a massively concurrent system with coroutines, have thousands of coroutines running at a time, and have 100% CPU usage most of the time. It all works great, but how can I give some coroutines higher priority? Sometimes I have work incoming that should be completed first, but because the application is already busy with other stuff the priority work has to wait for other work to finish before being processed. Alternatively, how can I start some coroutines on a low-priority thread, which should let me achieve the same goal?
    o
    d
    • 3
    • 4
  • m

    Mark

    07/06/2020, 2:22 AM
    When querying an Android
    ContentResolver
    you can optionally pass a
    CancellationSignal
    argument. So I would like to call
    cancel()
    on that object when the coroutine is cancelled. Is there a way to do this without using
    suspendCancellableCoroutine
    (since I don’t need the whole
    resume()
    functionality)?
    suspendCancellableCoroutine<Result> { continuation ->
        val cancellationSignal = CancellationSignal()
    	continuation.invokeOnCancellation { 
        	cancellationSignal.cancel()
    	}
    	val result: Result = resolver.query(args, cancellationSignal)
    	continuation.resume(result)
    }
    o
    • 2
    • 5
  • b

    bbaldino

    07/06/2020, 5:11 PM
    I've got some code that is basically a hierarchy of sub-tasks that I think would be a good fit to migrate to coroutines, but I've got some dumb questions trying to get a few things straight. 1. Is the proper way to propagate a failure up the chain (from, say any child task in that hierarchy) to define a set of custom exceptions to encode different events and use those? If so, is an exception typically used even for a non-error "finished" case? (one of the sub-tasks can finish on its own for a non-error reason, so I could define something like a "FinishedSuccessfully" exception for that? Or is there a better pattern to use there?) 2. If object A has a coroutinescope defined and creates object B--which will launch its own child coroutines--and I want object B's coroutines to be launched within object A's coroutinescope, is the best way to just have object A pass its scope to object B in the ctor (or in function calls)? Or is there a better way to (implicitly?) have B 'inherit' A's coroutine scope?
    e
    • 2
    • 18
  • m

    Maciek

    07/06/2020, 6:18 PM
    I'm wondering how to structure the code inside the class where I need something like an interval from RxJava, that'll do heavy operation every 50ms. The problem is that I'd want the channel producer to execute heavy operation only when someone is collecting the flow. I don't want to waste resources. Is there some easy way to achieve it?
    Untitled.kt
    👀 1
    d
    • 2
    • 10
  • a

    Aritracrab

    07/06/2020, 8:52 PM
    This might be a trivial questions for most of you. But can anyone please point me to an article/ list of articles which dig deep in inner workings of coroutines. I mean elaborate details of thread vs coroutines... Coroutine contexts ... Etc
    g
    r
    • 3
    • 2
  • t

    Tim Malseed

    07/06/2020, 11:50 PM
    I’m not usually one to post an SO question, but i feel like it’s relevant here, and it could use some more attention: https://stackoverflow.com/questions/62747825/coroutine-stateflow-stops-emitting-when-coroutinescope-is-cancelled
    z
    b
    • 3
    • 17
  • l

    Luis Munoz

    07/07/2020, 4:54 PM
    when using callbackFlow I need to clean up resources but when the job is canceled awaitClose isn't being called. How do I invoke awaitClose on a cancellation of the job
    fun listen(port: Int = 1337, nThreads: Int = 2) =  callbackFlow<String> {
    
                    val ch = b.bind(port).coAwait { }
                    for (obj in coReceiveChannel) {
    
                        send(obj)
                    }
    
                      awaitClose {
                        coReceiveChannel.cancel()
                        ch.close()
                       }
                
          } // end of listen
          
    job = listen().onEach { println(it) }.launchIn(scope)
            
    job.cancel()   // doesn't call awaitClose
    z
    s
    e
    • 4
    • 6
  • z

    zak.taccardi

    07/07/2020, 10:31 PM
    How can you emulate `ContentLoadingProgressBar`’s behavior in a
    Flow<T>
    ? Specifically, if I begin observing a
    Flow<ViewState>
    and it emits no
    ViewState.Loaded
    in the first 300ms, I want to emit a
    ViewState.Loading
    while ensuring that this
    ViewState.Loading
    emits before any
    ViewState.Loaded
    from the source
    Flow<ViewState>
    ? Kind of equivalent to:
    val sourceFlow: Flow<ViewState> = ..
    
    sourceFlow
      .onStart {
        delay(300)
        // if `sourceFlow` has not emitted any items yet
        emit(ViewState.Loading)
      }
    https://developer.android.com/reference/androidx/core/widget/ContentLoadingProgressBar
    l
    u
    e
    • 4
    • 8
  • a

    andylamax

    07/08/2020, 4:16 AM
    how do I map from a
    (Mutable)StateFlow<T>
    to another
    (Mutable)StateFlow<T>
    ? when I call the
    map
    method I map the
    StateFlow<T>
    to a
    Flow<T>
    t
    z
    • 3
    • 7
  • a

    antrax

    07/08/2020, 10:47 AM
    @elizarov it seems I can't find native-mt version for Kotlin 1.4-M3 in Maven (only M2 is there). Is it going to be released soon?
    e
    • 2
    • 2
  • j

    jdemeulenaere

    07/08/2020, 1:56 PM
    How can I somehow suspend until a flow starts to be collected to make sure that a collector will receive the first values that will be emitted in the flow ? Example of code to fix (https://pl.kotl.in/-sNdWODnA):
    package com.example.script
    
    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    
    fun main() {
        val count = MutableStateFlow(0)
        
        runBlocking {
            // Collect the values in a new coroutine.
            val job = launch {
                // Prints "3 4 5".
                count.take(3).collect {
                    println("$it ")
                }
            }
            
            // TODO: Somehow synchronize and suspend here until the coroutine starts collecting
            // so that we print "0 1 2" instead.
            
            repeat(3) {
                count.value++
            }
            
            repeat(3) {
                delay(500)
                count.value++
            }
        }
    }
    s
    m
    +3
    • 6
    • 8
  • a

    aballano

    07/08/2020, 2:32 PM
    Hi there, I’m facing an issue when declaring an suspended overload of a function
    interface ASyntax {}
    interface BSyntax : ASyntax
    
    fun hello(f: ASyntax.() -> Unit) = println("A")
    suspend fun hello(f: BSyntax.() -> Unit) = println("B")
    
    fun f1() = hello {  } // Might work or cause a compiler error because it resolves to the suspended version
    suspend fun f2() = hello {  } // Will call any hello version, but which one is unknown at first place
    
    suspend fun main() {
        f1()
        f2()
    }
    The problem is that depending on the case, either f1 will cause a compilation error because it resolves to the suspended version or f2 will resolve to the non-suspended version. So I’m wondering if someone knows if this is doable and it might be a bug (that I can report) or this is not really intended to be a thing in the first place (and I should rename one of the hello functions instead)
    o
    • 2
    • 1
  • c

    conner

    07/08/2020, 9:36 PM
    if i'm using a JNI/native library, and the jvm crashes (
    SIGSEGV (0xb)
    ,
    C  [libsystem_pthread.dylib+0x15ad]  pthread_mutex_lock+0x0
    ) when the value is created outside of a
    callbackFlow
    but not when it's inside, what would that mean? in other words,
    val thing = createNativeThing()
    callbackFlow {
      thing.onCallback = {
        offer(it)
      }
      thing.start()
    }
    crashes but
    callbackFlow {
      val thing = createNativeThing()
      thing.onCallback = {
        offer(it)
      }
      thing.start()
    }
    does not
    🤔 1
    g
    t
    • 3
    • 14
  • s

    Sam

    07/09/2020, 9:03 AM
    Hello everyone, I have problem with Coroutine - Flow and retrofit Does anyone know why Coroutine doesn’t work with QueryMap? Thanks.
    Not Work:
    
    @GET("/users")
        suspend fun getUsers(
                @QueryMap params:Map<String,Any>): BaseResponse<List<UserDto>>
    
    
    Worked: 
    @GET("/users")
        suspend fun getUsers(
                @Query("lat") lat:Double,
                @Query("long") lon:Double,
                @Query("genders")genders: String,
                @Query("age_max") ageMax:Int,
                @Query("age_min") ageMin:Int
        ): BaseResponse<List<UserDto>>
    My Repository implement:
    fun search(params:Map<String,Any>) = flow {
            emit(service.getMatchedUsers(params
            ).data.map {
                it.mapToDomainModel() }.toList())
        }
    l
    j
    • 3
    • 3
  • a

    Ayoub

    07/09/2020, 2:30 PM
    Hello, is there a way to declare a stateFlow without an initial value ?
    z
    g
    • 3
    • 3
  • r

    Ryan Simon

    07/09/2020, 8:47 PM
    hey all, got a super weird
    Flow<T>
    situation that I'd love to get some feedback on. the gist is that I'm wanting to transform some
    Flow<T>
    to some
    Flow<R>
    , where the
    transform
    function receives a
    Result<T>
    , but should spit out a
    Result<R>
    to line up with the return type of my function here's what the existing code looks like
    override fun getEquipment(type: String): Flow<Result<List<Equipment>>> {
            return apiCallHandler.process { equipmentApi.getEquipment(type) }
                .transform { result ->
                    result.onSuccess { response ->
                        if (response.equipment.isNotEmpty()) {
                            val equipmentList = ArrayList<Equipment>()
    
                            for (equipment in response.equipment) {
                                equipmentList.add(equipment.toEquipment())
                            }
    
                            emit(Result.success(equipmentList))
                        } else {
                            emit(Result.failure(EquipmentDataFailure.NoEquipmentFound))
                        }
                    }
                }
        }
    The main issue here is that if the
    result.onSuccess
    is never hit, the Flow will not emit anything and we won't know about it
    From what I can tell, this is because the
    result
    parameter given to us in the
    transform
    lambda is of type
    Result<T>
    , so if we just pass it through the
    Flow
    , it will terminate the
    Flow
    because we're expecting a
    Flow
    with a
    Result<R>
    (that's List<Equipment> in the example above) The way to work around this is to handle the
    result.onFailure
    case and
    emit
    from there. The thing is that there's no hint at having to do this from the IDE/compiler. Am I doing something I shouldn't be? And if not, maybe this is something that should be filed with the Kotlin team? Weird one for sure.
    o
    • 2
    • 13
Powered by Linen
Title
r

Ryan Simon

07/09/2020, 8:47 PM
hey all, got a super weird
Flow<T>
situation that I'd love to get some feedback on. the gist is that I'm wanting to transform some
Flow<T>
to some
Flow<R>
, where the
transform
function receives a
Result<T>
, but should spit out a
Result<R>
to line up with the return type of my function here's what the existing code looks like
override fun getEquipment(type: String): Flow<Result<List<Equipment>>> {
        return apiCallHandler.process { equipmentApi.getEquipment(type) }
            .transform { result ->
                result.onSuccess { response ->
                    if (response.equipment.isNotEmpty()) {
                        val equipmentList = ArrayList<Equipment>()

                        for (equipment in response.equipment) {
                            equipmentList.add(equipment.toEquipment())
                        }

                        emit(Result.success(equipmentList))
                    } else {
                        emit(Result.failure(EquipmentDataFailure.NoEquipmentFound))
                    }
                }
            }
    }
The main issue here is that if the
result.onSuccess
is never hit, the Flow will not emit anything and we won't know about it
From what I can tell, this is because the
result
parameter given to us in the
transform
lambda is of type
Result<T>
, so if we just pass it through the
Flow
, it will terminate the
Flow
because we're expecting a
Flow
with a
Result<R>
(that's List<Equipment> in the example above) The way to work around this is to handle the
result.onFailure
case and
emit
from there. The thing is that there's no hint at having to do this from the IDE/compiler. Am I doing something I shouldn't be? And if not, maybe this is something that should be filed with the Kotlin team? Weird one for sure.
o

octylFractal

07/09/2020, 8:50 PM
I don't know if there's anything that unexpected about this, I think the only thing I might suggest is that
transform
is a
1 -> N
mapping, where N can be zero, but
map
is a
1 -> 1
mapping, which is what I think you were going for
to me I would read this as you intended for failure to not do anything, as you explicitly handle only success
👍🏾 1
r

Ryan Simon

07/09/2020, 8:54 PM
yeah, maybe
map
is the better operator for my use case though what I really wanted was for the
Result
to pass through if it wasn't successful my
process
function returns a
Result<T>
that may or may not be a
success
. if it's not a
success
, i want the
failure
to just pass through without being touched by the
transform
o

octylFractal

07/09/2020, 8:57 PM
here's my suggestion: https://gist.github.com/octylFractal/dffc4887566964e25fdb7b80738ceab3
👍🏾 1
(1)
Flow.map
to ensure 1 -> 1 (2)
Result.mapCatching
to handle success/failure in mapping to new result (3)
equipment.map
for a simpler transformation to List
docs on `mapCatching`: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/map-catching.html
r

Ryan Simon

07/09/2020, 9:03 PM
i'll give that a shot, thank you!
@octylFractal maybe you can help me with this new interesting nugget lol. here's my new function
override fun getEquipment(type: String): Flow<Result<List<Equipment>>> {
        return apiCallHandler.process { equipmentApi.getEquipment(type) }
            .map { result ->
                result.mapCatching { response ->
                    if (response.equipment.isEmpty()) {
                        throw EquipmentDataFailure.NoEquipmentFound
                    } else {
                        response.equipment.map { it.toEquipment() }
                    }
                }
            }
    }
Now I get this error from the compiler:
org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node:
emit$$forInline (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;:
i can't win 😢
o

octylFractal

07/09/2020, 9:15 PM
looks like https://youtrack.jetbrains.com/issue/KT-34708
I suspect a potential workaround is to extract the content of
.map
to a separate function
r

Ryan Simon

07/09/2020, 9:16 PM
lol i just had to be the guy to find the bleeding edges. thanks again, Octavia
👍 1
confirmed that this was indeed related to that issue, and the latest EAP for Kotlin 1.4 fixed the problem for me.
👍 1
View count: 4