Одним из возможных решений является написание пользовательского ObservableTransformer
.На мой взгляд, самое простое решение - разделить элементы по группам в соответствии со следующим правилом: если cell.Id! = PreviousCell.Id поместить его в другую группу.
data class Cell(val id: Int, val childId: Int)
Observable.fromIterable(cells)
.map(object: Function<Cell, Pair<Int, Cell>> {
var latest: Int? = null
var groupNumber: Int = 0
override fun apply(t: Cell): Pair<Int, Cell> {
if(t.id != latest) {
latest = t.id
groupNumber++
}
return Pair(groupNumber, t)
}
})
.groupBy { it.first }
После этого все последовательные ячейки с одинаковымиid
будет в одной группе.Теперь вы можете делать все, что хотите.Для получения ожидаемого результата используйте следующий подход:
Observable.fromIterable(cells)
.map(object: Function<Cell, Pair<Int, Cell>> {
var latest: Int? = null
var groupNumber: Int = 0
override fun apply(t: Cell): Pair<Int, Cell> {
if(t.id != latest) {
latest = t.id
groupNumber++
}
return Pair(groupNumber, t)
}
})
.groupBy { it.first }
.flatMapSingle { group ->
return@flatMapSingle group.reduce(Pair(group.key!!, mutableListOf())) { acc: Pair<Int, MutableList<Int>>, el: Pair<Int, Cell> ->
acc.second.add(el.second.childId)
return@reduce acc
}
}.toList()
.subscribe({
Log.d("TAG", it.toString())
}, { e -> e.printStackTrace() })
Выход будет [(1, [1, 2, 3]), (2, [5, 6]), (3, [23, 18])].
Это решение не чистое, но оно работает так, как вам нужно.