private HashMap<Integer, Item> items = new Hashmap<>();
private Flowable<Item> observeItemById(int id) {
return Flowable.create(emitter -> {
???
},BackpressureStrategy.LATEST);
}
private Flowable<List<Item>> observeItems() {
return Flowable.create(emitter -> {
???
},BackpressureStrategy.LATEST);
}
//For now I update my hashmap just by putting new items or updating their fields in Item object
Each time when I call these functions I would like to create "new instance" of those functions / "new listener". When I invoke observeItems() I would like to emit list when there will be any changes in that list. But when I call observeItemById(int id), it should be emitted when there will be a change in that Item object.
How should I create these functions?
How should I create my hashmap and later update it to emit these changes?
For example:
class Item
class ObservableHashMap(private val map: MutableMap<Int, Item> = mutableMapOf()) : MutableMap<Int, Item> by map {
private val changesSubject = PublishSubject.create<Pair<Int, Item>>()
override fun put(key: Int, value: Item): Item? {
return map.put(key, value).also {
changesSubject.onNext(Pair(key, value))
}
}
override fun remove(key: Int): Item? {
return map.remove(key)?.also { value ->
changesSubject.onNext(Pair(key, value))
}
}
fun observeItemById(id: Int): Flowable<Item> {
return changesSubject.toFlowable(BackpressureStrategy.LATEST)
.filter { (key) -> key == id }.map { (_, value) -> value }
}
fun observeItems(): Flowable<List<Item>> {
return changesSubject.toFlowable(BackpressureStrategy.LATEST)
.map { values.toList() }
}
}
you could create a wrapper that returns a Flowable. Then you should override put function and emit the change with that Flowable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.