Hi,
Is it possible to observe a map list?
This is my map:
var map = mutableMapOf<Int, Long>()
I would like to notify to UI when the list gets any changes, is it possible?
My goal is to observe a map, so if there are others way to reach my objective, please let me know. Thanks
You can use rx to achieve that. Simplest things that I would do are:
- Create a subject. (PublishSubject)
- Modify your mutable Map/List somewhere
- Publish the result via
onNext
method on subject
- Observe the changes on UI via
subscribe
method from observable. If you’re on android, don’t forget to use .observeOn(AndroidSchedulers.mainThread())
.
Tips: you can use [aSubject].hide()
method to return an observable from a subject.
Good luck.
rxJava: GitHub - ReactiveX/RxJava: RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
rxKotlin: GitHub - ReactiveX/RxKotlin: RxJava bindings for Kotlin
There’s no way to observe a Kotlin Map. Like @ptdede suggests, your best bet is probably to put the map inside an observable object. For Android I’d suggest your UI observe a LiveData, and every time your code updates the map it should also call liveData.setValue(myMap)
.