Reputation: 5083
There are 2 streams. Stream #1 loads data from the server for autocomplete input. Stream #2 is user input from that autocomplete input. User can type while data is loading. Data is loaded once. When it is loaded, data is searched by all values which the user typed. It is required to search all inputs user made even when data was not available.
I think with marbles it is much easier to explain my problem. Here I am using combineLatest:
1 is loaded data. A,B,C,D are user input. What I am trying to achieve is to get 1A before 1B.
I need such flow:
User types: c - nothing happens
User types: r - nothing happens
Data is loaded: search is made for 'c' and for 'cr'
User types: o - search is made for 'cro'
User types: c - search is made for 'croc' and so on...
How can I achieve this with combineLatest or with another function?
Upvotes: 1
Views: 200
Reputation: 9929
Something like this can be achieved using a ReplaySubject
for the text input that waits to start emitting (and when it does replay all items to start with) until the initial data is loaded.
For example :
@JvmStatic
fun main(string: Array<String>) {
val input = ReplaySubject.create<String>()
val api = PublishSubject.create<Int>()
input.delaySubscription<Int>(api)
.withLatestFrom(api, BiFunction<String, Int, Pair<String, Int>> { t1, t2 -> Pair(t1, t2) })
.subscribe { println("Group : Letters : ${it.first}, Search with : ${it.second}") }
input.onNext("A")
input.onNext("AB")
api.onNext(1)
input.onNext("ABC")
input.onNext("ABCD")
input.onNext("ABCDE")
api.onNext(2)
input.onNext("ABCDEF")
input.onNext("ABCDEFG")
input.onNext("ABCDEFGH")
}
Output :
Group : Letters : A, Search with : 1
Group : Letters : AB, Search with : 1
Group : Letters : ABC, Search with : 1
Group : Letters : ABCD, Search with : 1
Group : Letters : ABCDE, Search with : 1
Group : Letters : ABCDEF, Search with : 2
Group : Letters : ABCDEFG, Search with : 2
Group : Letters : ABCDEFGH, Search with : 2
Upvotes: 2