Use IResults from CanClose

Topics: Actions & Coroutines
Feb 7, 2013 at 6:47 PM
I'm using IResults for example for FileDialog and Message box dialogs.
I need to use these from the CanClose function because I must let the user have a chance to save unsaved docs when closing app. How can I use IResult from a method that does not let you reuturn Enumerable of IResult?
Feb 19, 2013 at 3:34 PM
I solved it like (maybe there is a better soluton?)
    public abstract class ShellViewModel : Screen
    {
        public ShellViewModel(IResultFactory resultFactory)
        {
            Result = resultFactory;
        }
        
        public IResultFactory Result { get; private set; }

        public override void CanClose(Action<bool> callback)
        {
            var cancel = false;
            var cancelCallback = new Action(() => cancel = true);

            EventHandler<ResultCompletionEventArgs> completed = (s, e) =>
            {
                if (!cancel)
                    base.CanClose(callback);
            };

            var results = CanClose(cancelCallback);
            if (results != null)
                Coroutine.BeginExecute(results.GetEnumerator(), null, completed);
            else 
                completed(null, null);

        }

        protected virtual IEnumerable<IResult> CanClose(Action cancelCallback)
        {
            return null;
        }
    }
Feb 19, 2013 at 6:39 PM
You don't need to call base class only call the callback with true to close and false to cancel closing:
public class ShellViewModel : Screen
{
    public override void CanClose(Action<bool> callback)
    {
        Coroutine.BeginExecute(CanClose().GetEnumerator(), null, (s, e) => callback(!e.WasCancelled));
    }

    protected virtual IEnumerable<IResult> CanClose()
    {
        //yield return new CancelResult();
        yield break;
    }
}
To cancel the closing a result should set WasCancelled to true. This is a minimal example:
public class CancelResult : IResult
{
    public void Execute(ActionExecutionContext context)
    {
        Completed(this, new ResultCompletionEventArgs() { WasCancelled = true });
    }

    public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}
Feb 20, 2013 at 2:18 PM
Thanks that cleaned it up some!