https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
rx
  • i

    iex

    02/11/2020, 3:51 PM
    another one 😅 it's not possible to instantiate
    LiveData
    with a fixed value (like `Observable`'s
    just
    ), without having to use
    MutableLiveData
    ?
    k
    m
    • 3
    • 12
  • u

    ursus

    02/13/2020, 2:44 AM
    fun resetService(service: Service, usage: Usage): Single<Foo> =
            getSubscriber()
                .map { it.subscriber }
                .flatMap { subscriber ->
                    Single
                        .fromCallable {
                            val credit = usage.credit ?: 0.0
                            if (subscriber.type == Type.CREDIT && creditAmount < service.resetPrice) {
                                throw InsufficientCreditException(creditAmount, service.resetPrice)
                            }
    
                            val product = getProduct(cache, service.productId)
                            val usageManagement = product?.usageManagement ?: error("UsageManagent is null")
                            val resetProductId = product.resetProductIdOverride ?: usageManagement.resetProductId
    
                            tupleOf(usageManagement.action, resetProductId)
                        }
                        .doOnSuccess {
                            store.setProcessingSubscriber(subscriber.id, isProcessing = true)
                        }
                        .flatMap { (action, resetProductId) ->
                            setService(action, resetProductId, null, null, null, null)
                        }
                        .doOnErrorOrCancel {
                            store.setProcessingSubscriber(subscriber.id, isProcessing = false)
                        }
                }
                .doOnSuccess { updateManager.enqueueUpdate() }
    p
    • 2
    • 6
  • i

    iex

    02/13/2020, 7:26 AM
    initially I thought the later is better, but when there are errors (e.g. api returns a http error status) the observable aborts, so on the next button press, nothing will happen! To prevent this I can use
    onErrorReturn
    on the api observable(s) but this leads to a bit unwieldy chains in particular when there are several calls...
    d
    u
    • 3
    • 7
  • n

    Nikola Milovic

    02/16/2020, 6:55 PM
    Hey guys, still new to RX, when I try to use observables to get result from firestore
    override fun loadDrillTypes(): Observable<ArrayList<DrillsType>> {
    
            val list = ArrayList<DrillsType>()
    
            firebaseFirestore.collection("drilltypes")
                .get()
                .addOnSuccessListener { documents ->
                    for (document in documents) {
                        val doc = document.toObject(DrillsType::class.java)
                        list.add(doc)
                    }
                }
                .addOnFailureListener { exception ->
                    Log.w("TAG", "Error getting documents: ", exception)
                }
            return Observable.just(list)   // delay(2, TimeUnit.SECONDS)
        }
    I get an empty ArrayList
    compositeDisposable += repository.loadDrillTypes()
                .subscribeWith(object : DisposableObserver<ArrayList<DrillsType>>() {
    
                override fun onError(e: Throwable) {
                    //if some error happens in our data layer our app will not crash, we will
                    // get error here
                }
    
                override fun onNext(data: ArrayList<DrillsType>) {
                    Log.d("TAG", data.toString())
                }
    
                override fun onComplete() {
                    Log.d("TAG", "COMPLETE")
                }
            })
        }
    But if i add the delay(2, seconds) then I get the normal result that I need... I am 100% sure there is a way around this without having it to be delayed. Or is the delay a standard practice?
    k
    • 2
    • 7
  • g

    gsala

    02/17/2020, 8:24 AM
    Hey. I have an Rx library I use to connect to a BLE device. This library has this function:
    fun connect(bluetoothDevice: BluetoothDevice) : Observable<RxBleConnection>
    . The reason this returns an
    Observable
    instead of a
    Single
    is that the life-cycle of the
    Observable
    is tied to the connection. So this observable will only ever emit one item, but it will stay alive without completing so the connection stays alive until we dispose. I want to wrap this to use coroutines instead. I'm thinking about having a function like
    suspend fun connect(bluetoothDevice : BluetoothDevice) : RxBleConnection
    , Any ideas on how to handle the life-cycle of the Observable? If I just use
    connectObservable.awaitFirst()
    it will take the first value, and dispose, which will stop the connection.
    k
    • 2
    • 3
  • a

    alexsullivan114

    02/18/2020, 2:41 PM
    You could probably use a combination
    share
    and
    buffer
    to get that behavior, but I'd honestly just go the behavior subject route.
    i
    z
    t
    • 4
    • 9
  • i

    iex

    02/25/2020, 3:33 PM
    I'll explain my problem in more detail. I have this in a class (more specifically Android's view model though this doesn't seem relevant)
    private val dealerAction: Single<DealerAction> = carDealersRepo.selectedCarDealer()
        .map {
            it.toDealerAction()
        }
    
    val dealerButtonTitle: LiveData<String> = dealerAction
        .map { it.toButtonTitle() }
        .toObservable()
        .toLiveData()
    When I navigate to a new screen, I change carDealersRepo's underlaying data. When I navigate back, I want that this view model re-fetches
    selectedCarDealer
    z
    • 2
    • 44
  • i

    iex

    02/25/2020, 4:03 PM
    next problem 🙈, I'm deriving another thing from `dealerAction`:
    private val dealerButtonTrigger: PublishSubject<Unit> = PublishSubject.create()
    
    init {
        dealerButtonTrigger.withLatestFrom(dealerAction.toObservable())
            .subscribe { (_, action) ->
                action.handle()
            }
    }
    Here, when I click (i.e. call
    dealerButtonTrigger.onNext(Unit)
    ) after updating the dealer and navigating back, it still gives me the first dealer. Shouldn't it get the updated value?
    z
    • 2
    • 7
  • i

    iex

    02/25/2020, 4:08 PM
    If works as expected if I use
    flatMap
    instead of
    withLatestFrom
    , but curious why
    withLatestFrom
    doesn't. I thought it will get the current value at the point of time I activate the subject.
    z
    • 2
    • 4
  • i

    iex

    02/26/2020, 7:20 AM
    Hi folks, how would I prevent showing a loading indicator when the data is "already there"? Let me explain: • We perform some api requests, typically `Single`s and show a loading indicator in
    doOnSubscribe
    • Now we navigate forwards and back. This causes the observer (fragment/view) to re-subscribe. • The api calls are not performed again, but
    doOnSubscribe
    is called, making the progress indicator show for a very short moment. -> How can we show the indicator only when the requests are being performed?
    p
    z
    • 3
    • 11
  • s

    Slackbot

    02/26/2020, 7:27 AM
    This message was deleted.
    p
    • 2
    • 1
  • n

    Nikola Milovic

    02/26/2020, 9:25 AM
    Hey guys, quick question. Where should I dispose of a disposable observer if i am not using it in neither activity nor viewmodel/ fragment etc. Instead I am using it in my backend. There is no onclear, ondestroyed nor anything. I only have a
    val observer = object : DisposableObserver<DrillsType>() {
    
                override fun onError(e: Throwable) {
                    Log.d("TAG", "error " + e.message)
                }
    
                override fun onNext(data: DrillsType) {
                    //onnext
                }
    
                override fun onComplete() {
                    Log.d("TAG", "COMPLETE")
                }
            }
            remoteDataSource.loadDrillTypes().subscribeWith(observer)
        }
    It should be disposed when it's all finished. Can I dispose of it in the onComplete perhaps 😂?
    p
    • 2
    • 2
  • n

    Nikola Milovic

    02/27/2020, 3:17 PM
    I have to beg people here who might have an elegant solution to this callback hell.. https://stackoverflow.com/questions/60431813/combining-multiple-firebase-callbacks-with-rxjava2
    k
    m
    p
    • 4
    • 9
  • m

    Matsushita Kohei

    03/01/2020, 12:12 AM
    Hi everyone!! Please tell me. Can Rx execute parallel processing like awaitAll of Kotlin coroutine? I think it is similar to "zip" but it can't use List<T>. I'm waiting for messages. thanks.
    z
    u
    p
    • 4
    • 7
  • d

    Danil Novoselov

    03/03/2020, 5:33 PM
    Hi there!! How you guy evaluate, if one rx-operator works slowler than another??
    z
    u
    • 3
    • 3
  • r

    Rich Lowenberg

    03/18/2020, 7:53 PM
    Hey everyone! I may be about to start an Android project that will likely be pure RxKotlin. Wondering how many people actually use that, and if there are any freelancers with significant Rx experience that might be available to help. If so please message me with a little about yourself, and let me know your level of experience and rate. My colleague and I are both former Googlers, working freelance for a start up based in Brooklyn.
    z
    a
    p
    • 4
    • 5
  • i

    ivano

    03/19/2020, 2:36 PM
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    ✝️ 2
    ➖ 2
    😂 1
    ➕ 10
    a
    • 2
    • 1
  • i

    ivano

    03/20/2020, 12:21 PM
    OPS SORRY, fell de phone on the keyboard
    😂 1
    • 1
    • 1
  • u

    ursus

    03/21/2020, 3:26 PM
    Can I persist/restore Observable from disc?
    z
    • 2
    • 8
  • i

    iex

    03/25/2020, 1:55 PM
    Is there anything in RxJava similar to this? https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#driver More specifically
    Can't error out
    I'd like that e.g. if I map a click button trigger to an api request an the api request fails, it executes again the next time the trigger is activated. Without having to create a new subscription each time.
    m
    p
    • 3
    • 14
  • i

    iex

    03/27/2020, 2:29 PM
    What would be a good pattern to make repositories, which usually just fetch data from retrofit APIs, fully reactive (i.e. offer long term subscriptions, not
    Single
    )? Maybe maintain
    BehaviorSubject
    with the API results from the last fetch, but when / how do I fetch?
    z
    b
    • 3
    • 3
  • u

    ursus

    04/07/2020, 4:00 PM
    How can I enforce only 1 execution of Observable/Single at the time? I know about maxConcurrency of flatMap, but that requires that flatMap to be on a top level in the chain If its inside say switchMap, then its all gone Semaphores maybe?
    t
    b
    • 3
    • 12
  • u

    ursus

    04/11/2020, 7:32 PM
    is this thread safe? It is not, right?
    z
    • 2
    • 7
  • y

    yougin

    04/15/2020, 12:13 PM
    Hey guys! Could you think of a better solution for emitting an event with a delay after the first emission from
    Observable
    ?
    just(1)
        .flatMap { just(2).delay(1, SECONDS).startWith(it) }
        .subscribe { println(it) }
    Just curious if I’m missing on some operator which does the thing.
    z
    u
    • 3
    • 7
  • w

    william

    04/27/2020, 8:24 PM
    i have a subscription which i want to outlast the fragment which it is created in - basically i only want it to die if the application dies. Is the best thing to do to have a
    CompositeDisposable
    for my entire application containing similar subscriptions or can i ignore the return value of
    .subscribe
    ?
    g
    a
    +2
    • 5
    • 11
  • u

    ursus

    05/03/2020, 9:07 PM
    Do you guys hop off from
    io
    to
    computation
    for your repository calls after networking?
    w
    e
    • 3
    • 2
  • g

    gabrielfv

    05/12/2020, 2:12 PM
    Is there a clean way to send a fire and forget request through rx? There's nothing to be done upon returning, so an empty
    .subscribe()
    would make sense, but if the request fails for some reason the app crashes because there is no
    onError
    handling. However, if I give it something so that it feels it has error handlung, like
    .subscribe({ }, { })
    , I'll be passing on indirect reference to the enclosing class, which would prevent it from being garbage collected until the request returned. Is there some sort of standard way of acting on such scenario?
    z
    j
    • 3
    • 4
  • n

    Nikola Milovic

    05/14/2020, 11:47 AM
    Can someone please explain this error message?
    Exception in thread "UI thread @coroutine#1" java.lang.ClassCastException: io.reactivex.Observer$Subclass1 cannot be cast to com.nikolam.basketpro.ui.drills.selection.DrillsSelectionViewModel$fetchDrillTypes$1$disposable$1
    	at com.nikolam.basketpro.ui.drills.selection.DrillsSelectionViewModel$fetchDrillTypes$1.invokeSuspend(DrillsSelectionViewModel.kt:37)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    I get a passing test with correct data but I also get this error (code in thread so I dont spam)
    • 1
    • 1
  • u

    ursus

    05/21/2020, 2:42 AM
    is there a safer operator I can use, which would give me the latest value or null, sort of like
    BehaviorRelay.value
    ?
    z
    • 2
    • 5
  • u

    ursus

    05/22/2020, 3:47 PM
    but I dont understand what you meant fully
    i
    • 2
    • 3
Powered by Linen
Title
u

ursus

05/22/2020, 3:47 PM
but I dont understand what you meant fully
i

ivano

05/23/2020, 6:10 PM
Well ok. I am trying to understand the basics of programming, as I am originally a financial guy. I read about algorithms where is written in the recursive pattern, that functional works not with loops iterations as 'for', but with recursion. But I understand from your reply l is not the case so rx kotlin is not a real functional paradigm, but a reactive declarative way to think namely an observer pattern with muscle
u

ursus

05/23/2020, 6:54 PM
depends how you think about it, its mostly imperative vs declarative
i

ivano

05/23/2020, 9:06 PM
Yes I see, is a distinction that is intrinsic in the world functional i guess, because functional is based on the concept of an input and an output. So you have an input and output also in OO. For instance you call a method function and the function returns a value. But functional is less based on methods and more at final variables, I am seeing clojure and understanding the concept. Then functional includes declarative but is not the same thing, are not synonyms, declarative is a level less abstract than functional, this generated problems to me relating to rxjava, but now I am grasping the surface. Uncle Bob said let the magic go away, learn assembly before than later. I do not want black magic, is stupid and annihilates the programmer abilities although is pragmatic. Is clear, I need to make dirty my hands with real functional code to understand the concept and not judge kotlin that does not add nothing (with all the due respect) to the existing code paradigms. To be honest I find irritating some reviews so long to write idiomatic kotlin or decide the last concurrency freak utility library
View count: 2