Let’s listen any changes made in Collection (List, Map or Set)

26 / Jul / 2015 by Aman Mishra 0 comments

Have you ever wondered how come your Collection is being updated and ended up spending time on debugging? We are going to see how can we get to know immediately if our Collection is altered. In this blog, we will do this using ObservableList for ‘List’ and same can be applied for Map and Set as well.

Here goes code to implement this :

import java.beans.*
def event
def listener = {
if (it instanceof ObservableList.ElementEvent) {
event = it
event = null
} as PropertyChangeListener

def logEvent (ObservableList.ElementEvent event) {
       println "New element ${event.newValue}, ${event.changeType} at Index ${event.index} and replaced ${event.oldValue}" 

/* Declare our list and add listener to listen any change*/
def observableList = [1, 2, 3] as ObservableList

If we don’t need an explanatory log then above block of code can be rewritten as :

def observableList = [1, 2, 3] as ObservableList
/*We can use newValue(), oldValue()and few more methods with 'it' but not changeType() and index() as these are in child class of PropertyChan geListener*/

Now it’s time to alter our list and see the change:

observableList.add 42
observableList.putAt(2, 10)
observableList.addAll([1, 2, 3, 4])

Result (For first snippet of code):

New element 42, ADDED at Index 3 and replaced null
New element null, REMOVED at Index 2 and replaced 3
New element 10, UPDATED at Index 2 and replaced 42
New element java.lang.Object@19d9744, MULTI_ADD at Index 2 and replaced java.lang.Object@1361c3f
New element java.lang.Object@19d9744, CLEARED at Index 0 and replaced java.lang.Object@1361c3f

Hope it helps :)

Tag -


Leave a comment -