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
rx
  • u

    ursus

    06/21/2019, 3:28 PM
    also how to let the messageId visible? I dont want to emit pairs everywhere
    g
    k
    a
    • 4
    • 34
  • u

    ursus

    06/21/2019, 4:00 PM
    or wait for Flow to get best of both worlds
    g
    • 2
    • 1
  • a

    adams2

    06/21/2019, 4:34 PM
    how do I easily use kotlin method references with rxjava subscribes?
    g
    l
    • 3
    • 5
  • k

    kioba

    06/24/2019, 4:32 PM
    You might want to look into MVI and how it is handling these problems. MVI is handling all the problem you raising. I can suggest to look into this:

    https://youtu.be/64rQ9GKphTg▾

    they way I would do it is:
    class ChatViewModel(private val messageManager: MessageManager): ViewModel {
      private val binder: PublishProcessor<MessageEvent> = PublishProcessor.create()
      private val state =
        binder
          .flatMap{ messageManager.editMessage(it.messageId, it.newText) }
          // #1
          .replay(1)
          .autoConnect(0)
    
      fun editMessageClick(messageId: Long, newText: String) {
        binder.onNext(MessageEvent(messageId, newText))
      }
      override fun state(): Observable = state
    }
    
    class MessageManager {
      fun editMessage(messageId, newText) = 
        database.update(messageId, newText, State.SENDING)
          .flatMap { apiClient.editMessage(...)}
          .flatMap { database.update(messageId, newText, State.SENT )}
          .asEvents()
    }
    
    data class MessageEvent(val messageId: Long, val newText: String)
    u
    • 2
    • 21
  • j

    jw

    06/25/2019, 4:29 PM
    like
    A.skipUntil(B.ignoreElements().concatWith(just(Unit)))
    m
    k
    u
    • 4
    • 5
  • k

    kioba

    06/25/2019, 4:46 PM
    I was thinking about buffering instead of skipping events from
    A
    while
    B
    is triggering
    m
    • 2
    • 1
  • m

    myanmarking

    06/26/2019, 11:41 AM
    return Observable.just(1)
        .doOnSubscribe{
            this.disposable = observable.just(2)
                .subscribe({...}, {...})
        }
    b
    • 2
    • 3
  • r

    rook

    07/01/2019, 1:13 PM
    The following can’t be resolved. The culprit seems to be the
    BiFunction
    , but I can’t figure out what specifically I’ve done incorrectly
    val one = Observable.fromIterable(listOf(1,2,3))
            val two = Observable.fromIterable(listOf(4,5,6))
            Observable.combineLatest(one, two, BiFunction{ p1:Int, p2:Int -> p1+p2})
    g
    a
    r
    • 4
    • 9
  • f

    fangzhzh

    07/03/2019, 11:53 PM
    read a article about scheduler https://lorentzos.com/i-bet-your-rxjava-is-on-the-wrong-thread-ae02e66a3eac
    fun printCurrentThread(tag: String) = println("$tag: ${Thread.currentThread().name.substringBefore("-")}")
    
    fun main(args: Array<String>) {
    	printCurrentThread("main thread name")
    
    	val subject = BehaviorSubject.create(Unit)
    
    	subject
    			.subscribeOn(Schedulers.computation())
    			.subscribe {
    				printCurrentThread("subscribe onNext")
    			}
    
    	Thread.sleep(100L)
    
    	subject.onNext(Unit)
    
    	Thread.sleep(100L)
    }
    
    // The author said the code gives
       main thread name: main
       subscribe onNext: RxComputationScheduler
       subscribe onNext: main
    
    The author explains:
    Correct answer is A because the default value is based on the subscribeOn (computation thread) and .onNext() of the subject is called from the main thread. Therefore the second emission will ignore the subscribeOn, change thread and will be emitted at the main thread.
    But from my running, it gives
    main thread name: main
    subscribe onNext: main
    my question is that is there really a
    Where the first RxComputationScheduler onNext()
    ?
    t
    • 2
    • 2
  • j

    Joan Colmenero

    07/04/2019, 9:57 PM
    on result I have to check if it's Failure or the List? And error is a server error?
    a
    • 2
    • 1
  • j

    Joan Colmenero

    07/08/2019, 3:59 PM
    Any idea? :https://stackoverflow.com/questions/56938378/how-to-return-a-maybe-or-result-from-maybe
    a
    • 2
    • 2
  • i

    ivano

    07/12/2019, 12:47 PM
    -.js
    t
    • 2
    • 2
  • u

    ursus

    07/15/2019, 12:29 AM
    What's the cleanest way to use Rx and inheritance?
    g
    • 2
    • 1
  • r

    reline

    07/15/2019, 5:25 PM
    hey guys, I’d like some help figuring out how to better handle errors emitted from this observable. I want to parse multiple files eagerly, then wait for all of them to complete, and know which files failed. Is this possible? This is what I have so far:
    fun parseObservable(f: File): Observable<Item> { ... }
    
    Observable.fromIterable(List<File>)
                    .concatMapEagerDelayError({ parseObservable(it) }, true)
                    .toList()
                    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe { items -> ... }
    r
    u
    • 3
    • 5
  • d

    Daniel Rodak

    07/18/2019, 7:14 AM
    Is there cleaner way to zip Observable with Completable? So
    actionIntent()
    returns Observable and
    loadFile()
    returns Completable. I want to zip them and return Boolean value of the observable. Is this the right way to fit Completable?
    -.txt
    g
    a
    • 3
    • 5
  • p

    pteale

    07/24/2019, 8:40 AM
    What’s the best way of doing this with Rx.. Get config with network call If that config is NOT available go to another endpoint to get the config If the first config is available pass back the JSON and don’t do that second call
    g
    u
    • 3
    • 3
  • j

    Joe

    07/25/2019, 10:02 PM
    I currently have a slow, synchronous, io-bound method that returns a
    Publisher<T>
    , and am doing
    buildPublisher().subscribe(subscriber)
    from an "outside of rx" thread/context. To free up that thread, I'd like to move the
    buildPublisher()
    call "into rx". Currently have the following, but not sure if there's a clearer, less error prone, or otherwise better way:
    Flowable.create<T>({ emitter -> 
      try {
        buildPublisher().subscribe(
            object : Subscriber<T> {
                override fun onComplete() {emitter.onComplete() }
                override fun onSubscribe(s: Subscription) { s.request(Long.MAX_VALUE) }
                override fun onNext(t: T) { emitter.onNext(t) }
                override fun onError(t: Throwable) { emitter.onError(t) }
            }
      } catch (e: Exception) { emitter.onError(e) }
    }, BackpressureStrategy.BUFFER)
        .subscribeOn(<http://Schedulers.io|Schedulers.io>())
        .subscribe(subscriber)
    s
    • 2
    • 5
  • t

    tseisel

    07/29/2019, 9:32 AM
    Given a
    Flowable
    that emits values and multiple errors (for example, after merging back the stream with
    flatMapSingle
    ), how can I prevent errors from terminating the
    Flowable
    , so that I can print errors along values ?
    g
    • 2
    • 1
  • u

    ursus

    08/02/2019, 1:45 PM
    what do you guys think about code like this, is this kosher?
    t
    p
    • 3
    • 24
  • a

    am414

    08/15/2019, 9:06 PM
    I need slightly help for using rxjava with retrofit I have a post request, the status code response could be 200 or 400+ depending on what I have sent, what I need is get the json as a "RegisterResponse" Object as we do on .subscreibe(//here) just to return it as MutableLiveData<RegisterResponse>() object the problem is I received the response as a string how I can changing it to be "RegisterResponse" object
    val data = MutableLiveData<RegisterResponse>()
     disposables.add(
                ServiceRepo.register(firstName, lastName, mobileno, email, password)
                    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        data.value = it
                    }, { throwable ->
            val error: HttpException = throwable as HttpException
                        if (error.code() == 400) {
                            val jObj = error.response().errorBody() as RegisterResponse//the issue here, i can't cast it 
                            data.value = jObj
                        }
    
                    })
            )
    a
    t
    b
    • 4
    • 4
  • b

    blakelee

    08/16/2019, 9:20 PM
    I have a Maybe that then does a switchIfEmpty. The switchIfEmpty is still firing even though the value isn’t empty, anyone see anything like this? I am able to evaluate the Maybe by using blockingGet and can see that I’m getting my items. I should also mention that it’s a Flowable.firstElement to get that Maybe. Not sure if that’s relevant. I am using () instead of {} for the switchIfEmpty so parts of it are working
    a
    • 2
    • 7
  • i

    ilyagulya

    08/19/2019, 4:08 PM
    Hello, guys! How could you do such thing?
    val a: Completable
    val b: Completable
    val c: Completable
    
    val merged = Completable.merge(listOf(a,b))
    I need to subscribe to both
    merged
    and
    c
    but if
    merged
    completes before the
    c
    , I need to unsubscribe from
    c
    .
    k
    e
    • 3
    • 9
  • b

    blakelee

    08/19/2019, 4:19 PM
    Pretty sure I broke switchIfEmpty 😕
    fun doThings(): Maybe<Boolean> {
        Log.d("TEST", "HIT")
        return Maybe.just(true) 
    }
    
    return Maybe.just("")
        .map { false }
        .switchIfEmpty(doThings())
    My log message still shows even though my Maybe is not empty
    k
    • 2
    • 11
  • a

    am414

    08/23/2019, 8:23 PM
    I'm a little bit New in Rxjava but I use it here with Retrofit + kotlin I have a request API that giving me a data for a specific page with a query ?page=1 and after I received the first page I will know how many pages we have, so my question is : how I can make loop request with changing query page number ?page={page number} and get all of them and combine them in a list. if it is a big question just give me what i have to do. thanks a lot have a nice weekend for all
    disposables.add(
                ServiceRepo.getProductReviews(context, pruductId)
                    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                      //how i can get them all here ♥
                    }, { throwable ->
                        Log.e("tag", throwable.message)
                    })
            )
    i
    a
    • 3
    • 2
  • t

    thanh

    08/27/2019, 6:40 PM
    Do I need to write a custom operator for it? Or we already have some kind of combination to get that function?
    ➕ 1
    d
    t
    i
    • 4
    • 13
  • b

    BMG

    08/29/2019, 7:45 AM
    My proposal,
    Single.fromCallable {
     getUser().isVerified
    }
    .flatMapObservable { 
     if(it) Observable.just(it)
    else getUserObservable().map { it.isVerified }
    }
    .subscribe ({
       if(it) view.showVerified
    })
    m
    e
    • 3
    • 2
  • g

    Grant Park

    08/29/2019, 6:43 PM
    such that if the last Single is an error, then the
    .doOnError
    of upstream Singles will be invoked
    b
    • 2
    • 1
  • f

    Fredrik Larsen

    09/04/2019, 12:00 PM
    I'm struggling with the TestScheduler and hoping that someone can render some insight. I've boiled the troublesome code down to this example:
    @Test
        fun `validate test`() {
            val scheduler = TestScheduler()
    
            val upstream = Flowable.fromCallable { "foo" }
                .subscribeOn(scheduler)
                .observeOn(scheduler)
                .delay(2, TimeUnit.SECONDS)
    
            val implementation = upstream
                .map { true }
                .startWith(false)
                .subscribeOn(scheduler)
                .observeOn(scheduler)
                .doOnEach { println(it) }
                .test()
    
            implementation
                .assertNotTerminated()
                .assertNoValues()
    
            scheduler.advanceTimeBy(1, TimeUnit.SECONDS)
    
            implementation
                .assertNotTerminated()
                .assertValues(false)
    
            scheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    
            implementation
                .assertNotComplete()
                .assertValues(false, true) /* assertion fails*/
    
            /*
            * Output:
            * 
            * OnNextNotification[false]
            * 
            * java.lang.AssertionError: Value count differs; expected: 2 [false, true] but was: 1 [false] (latch = 1, values = 1, errors = 0, completions = 0)
            *   Expected :2 [false, true] 
            *   Actual   :1 [false] (latch = 1, values = 1, errors = 0, completions = 0)
            */
        }
    k
    • 2
    • 6
  • b

    BMG

    09/04/2019, 2:17 PM
    Ah correct! Is there any valid use case for
    blockingGet()
    ?
    a
    m
    • 3
    • 3
  • a

    alexsullivan114

    09/16/2019, 1:54 PM
    thoughts?
    s
    • 2
    • 1
Powered by Linen
Title
a

alexsullivan114

09/16/2019, 1:54 PM
thoughts?
s

starke

09/16/2019, 5:54 PM
I think the pre-share code is more straightforward. having to call
subscribe
multiple times and potentially deal with managing multiple disposables doesn’t add much value
View count: 4