Adding CollectionChanged Notification to an Observable Collection causes odd behavior

DavidPatterson.0554DavidPatterson.0554 USMember
edited November 9 in Xamarin.iOS

I have a post at on stackoverflow with title xamarin-iphone-android-pass-by-reference but was recommended I post here as well.

I have two viewcontrollers within a Tabbar controller. The view controller below is the second tab. I am running into some interesting functionality with CollectionChanged notify events. FYI this code just listens to updates in the manager and updates the view when changes occur. The design works correctly on android. After a model is not read from a bluetooth module after a certain amount of time a timer event is triggered and the model is removed from an observable collection list. The list then triggers an event in the viewcontroller to update the table. Whenever i subscribe to changes in the list with the line manager.modelList.CollectionChanged += UpdateView; the remove function in the model is never properly executed. If I remove the subscription it works correctly. Any ideas what the problem might be? I've read another forum post at forums xamarin tableview-reloaddata-equivalent-for-listview and it seems similar. (sorry unable to post direct links)

public partial class ViewController: UIViewController
{
    private List<Model> itemList;
    private BlueTooth ble;
    private UITableView deviceTable;

    public ViewController (IntPtr handle) : base (handle)
    {
    }

     public override void ViewDidLoad ()
     {
    ble = BlueTooth.Instance;
        manager = ble.getManager();
        itemList = manager.modelList.ToList();
        manager.modelList.CollectionChanged += UpdateView;

        deviceTable = new UITableView
        {
             Source = new DeviceTableSource(itemList)
        };
        View.AddSubview(deviceTable);
      }

     void UpdateView(object sender, EventArgs e)
     {
        itemList = ble.getManager().ModelList.ToList();
        deviceTable.Source = new DeviceTableSource(itemList);
        deviceTable.ReloadData();
     }
}

Manager Class

class Manager{
   public ObservableCollection<Model> modelList {get; set;}

   public Manager(){
     modelList= new ObervableCollection<Model>();
   }

  public addModel(){
   Create a Model object with reference to ModelList
   Add Model to ModelList
  }

  public updateModel(){
    update Model in List        
  }
}

Model Class

class Model{
    private ObservableCollection<Model> list;
    private Timer removeTimer;

        Model(modelList){
            removeTimer += onTimedEvent
         }

        OnTimedEvent(){
            removeDevice();
        }

        removeDevice(){ 
            modelList.remove(this);
            Console.writeLine("Device Removed");
        }
    }

Answers

  • iphooiphoo BYMember ✭✭
    edited November 13
    Your timer callback function may be executed not on UI thread; it should crash the app.
Sign In or Register to comment.