I'm a bit of an RxJava newbie. I'm getting the hang of it, but there's one scenario that I'm not quite satisfied with. Say I have a pair of Observables of different types that are designed to work together. For example:
val list: Observable<List<MyClass>>
val indexIntoList: Observable<Int>
So, I need to observe these as a pair, so that the observer gets emitted to when either list or indexIntoList gets an update. Right now my solution is something like this:
var lastListUsed: List<MyClass> = ArrayList()
var lastIndexUsed = -1
val syncObject = Object()
init {
list.subscribe(object: Observer<List<MyClass>>{
.
.
.
override fun onNext(t: List<MyClass>)
{
FunctionOnMyClass(t, lastIndexUsed)
}
})
indexIntoList.subscribe(object: Observer<Int>{
.
.
.
override fun onNext(t: Int)
{
FunctionOnMyClass(lastListUsed, t)
}
})
}
fun FunctionOnMyClass(list: List<MyClass>, index: Int)
{
synchronized(syncObject)
{
lastListUsed = list
lastIndexUsed = index
.
.
.
}
}
I had the thought to do something like this:
var lastMyClass = DefaultMyClass()
list.doOnNext{listVersion ->
indexIntoMap.map{ index ->
if(index in listVersion.indices)
listVersion[index]
else
lastMyClass
}.subscribe(object: Observer<MyClass>{
.
.
.
override fun onNext(t: MyClass)
{
lastMyClass = t
.
.
.
}
})
}
But if I'm understanding correctly, to use this method, I would have to dispose the Disposable on the inner Observable every time the outer Observable updates. I'd rather not do that. Is there a preferred way to handle this scenario? Should I be open to disposing the Disposable on every update of the outer Observable?