https://kotlinlang.org logo
#rx
Title
k

kluck

02/23/2018, 2:48 PM
Hello guys, I'm looking for a way to kind of combine throttleFirst and distinctUntilChanged: if I have 2 distinct elements, no matter the delay between the emissions, I want to receive both. But if I get the same element multiple times, I want it to be throttled and get one, say every 2s. Any idea how I could manage that?
r

rakeeb

02/24/2018, 6:05 PM
I think since you need closely want to monitor your values, you could use the
materialize
operator and have your own logic there. or I might be completely wrong here!
k

kluck

02/26/2018, 9:49 AM
I'll try with
materialize
, thank you!
r

rakeeb

02/28/2018, 1:33 AM
on second thought,
materialize
might be a bit overkill. use the
scan
operator
Copy code
val scanningSequence = Observable.fromIterable(listOf(1, 1, 2, 3, 5, 5))
        .scan(Pair(0, false), { lastEmission: Pair<Int, Boolean>, current: Int ->  
            if(lastEmission.first != current) return@scan Pair(current, false)
            return@scan Pair(current, true)
        })
        .flatMap { 
            if(it.second) {
                return@flatMap Observable.just(it.first)
                        .throttleFirst(2, TimeUnit.SECONDS)
            }
            return@flatMap Observable.just(it.first)
        }
k

kluck

02/28/2018, 9:55 AM
In the end, I managed to avoid my problem altogether. But I didn't know either about the scan operator. It seems quite handy!
2 Views