ReactiveUI, get a list from a viewmodel when navigated to - if the viewmodel implements interface

StackOverflow https://stackoverflow.com/questions/21419102

  •  04-10-2022
  •  | 
  •  

Question

I'm using ReactiveUI and its Router.

Some of my IRoutableViewModels implements a interface IHaveCommands, which have a property IEnumerable<IReactiveCommand> Commands { get; }

So, what I want, is a list of commands for the current viewmodel in my IScreen implementation, the AppBootstrapper.

What would be 'the right' way of implementing this?

I have sort of got it to work with the following code, but my guts tells me that there are other, better ways of doing it....

public class AppBootstrapper :  ReactiveObject, IScreen
{
    public IRoutingState Router { get; private set; }

    public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null)
    {
        Router = testRouter ?? new RoutingState();

        Router.CurrentViewModel.Where(x => x != null)
               .Select(x => typeof(IHaveCommands).IsAssignableFrom(x.GetType()) ? ((IHaveCommands)x).Commands : null)
               .ToProperty(this, x => x.Commands, out _toolbarCommands);

        ...
    }

    readonly ObservableAsPropertyHelper<IEnumerable<CommandSpec>> _toolbarCommands;
    public IEnumerable<CommandSpec> ToolbarCommands { get { return _toolbarCommands.Value; } }

}

Any tips?

Was it helpful?

Solution

This looks great to me! Other than some possible minor readability fixups, this is What You Should Do™. Here's a slightly cleaner version:

Router.CurrentViewModel
    .Select(x => {
        var haveCmds = x as IHaveCommands;
        return haveCmds != null ? haveCmds.Commands : null;
    })
    .ToProperty(this, x => x.Commands, out _toolbarCommands);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top