In Android-Binding, if you need to “observe” an Observable, you can implement DependentObservable or simply the Observer.

For ObservableCollections (i.e. CursorCollection / ArrayListObservable),  the change of collection items is not notified. If you need to know the changes of collection items, you need CollectionObserver.

Collection Observer will raise in following situations:

  1. Item Added
  2. Item Remove
  3. Item Replaced
  4. Item Moved
  5. Collection Resetted (Cleared, Requery, etc)

All these information is given in the CollectionChangedEventArgs.

Example – Collection Size Converter

In a recent project, I need to show the number of items in an collection. So, I made a simple converter named COLLECTION_SIZE. It takes only one argument, which is the collection, and returns an integer of the number of items in it. Here is the code:

public class COLLECTION_SIZE extends Converter<Integer> {
	public COLLECTION_SIZE(IObservable<?>[] dependents) {
	    super(Integer.class, dependents);
    }

	private IObservableCollection<?> mCol = null;

	@Override
    public Integer calculateValue(Object... arg0) throws Exception {
		IObservableCollection<?> collection = (IObservableCollection<?>)arg0[0];
		if (mCol != collection){
			if (mCol!=null){
				mCol.unsubscribe(observer);
			}
			mCol = collection;
			collection.subscribe(observer);
		}

		return collection.size();
    }

	private CollectionObserver observer = new CollectionObserver(){
		@Override
        public void onCollectionChanged(IObservableCollection<?> arg0,
                CollectionChangedEventArg arg1, Collection<Object> arg2) {
			COLLECTION_SIZE.this.setDirty(true);
			COLLECTION_SIZE.this.notifyChanged();
        }
	};
}
About these ads