Ryan Langton
Ryan Langton

Reputation: 6160

Triggering event in Activity using MvvmCross

I have an MvxFragmentActivity which loads a google map and places markers on the map. The code to create the map and markers is very Droid specific so it is in the Activity. The markers are created based on objects in the ViewModel which each contain lat/long coordinates. This worked fine as long as I loaded the objects in my Init method. I have since moved the load objects method to a service and call it on a different thread. This way the UI is responsive. However, how do I call the method in the Activity when the load is completed?

Here is my current code in the Activity (this code shouldn't change, just how it is called):

    private void InitMapFragment()
    {
        foreach (var item in viewModel.Items)
        {
            var icon = BitmapDescriptorFactory.FromResource(Resource.Drawable.place_img);
            var markerOptions = new MarkerOptions()
                .SetPosition(new LatLng(item.Latitude, item.Longitude))
                .InvokeIcon(icon)
                .SetSnippet(item.DistanceText)
                .SetTitle(item.Name);
            var marker = _map.AddMarker(markerOptions);
            _markerIds.Add(marker.Id, item.Id);
        }
   }

Code in my viewModel:

    private void BeginLoadItems()
    {
        _loadItemsService.Load();
    }

    // This is triggered by a message
    private void OnLoadItemsComplete(LoadCompleteMessage message)
    {
        Items = message.Items;
    }

Code in my Service:

    public void Load()
    {
        ThreadPool.QueueUserWorkItem(state =>
            {
                var results = _repository.Retrieve();
                _messenger.Publish(new LoadCompleteMessage(this, results));
            });
    }

Upvotes: 1

Views: 517

Answers (1)

Stuart
Stuart

Reputation: 66882

You're already triggering an event when you set:

    Items = message.Items;

This triggers PropertyChanged with a property name of "Items"

For more on map binding, see Using MvvmCross how can I bind a list of annotations to a MapView? - although with Droid you'll need to use markers instead of annotations.

Upvotes: 1

Related Questions