ReactiveUI: How to pass a parameter to ReactiveCommand.CreateFromTask correctly
Asked Answered
J

1

7

I want to pass a parameter from my View to my ViewModel when a ReactiveCommand is executed that is bound to a Control. The parameter should be of type IJcUser

So I define the Command like this:

public ReactiveCommand<IJcUser, Unit> UserTouchCommand;

UserTouchCommand = ReactiveCommand.CreateFromTask(user => RootViewModel.DisplayUserProfile(user));

The signature of DisplayUserProfilelooks like

Task DisplayUserProfile(IJcUser user);

But the compiler complains because useris from type CancelationTokenand not as expected IJcUser

I finally I found a solution but don't understand why the first approach did not work.

UserTouchCommand = ReactiveCommand.CreateFromTask<IJcUser>(RootViewModel.DisplayUserProfile);
Jevons answered 25/1, 2017 at 12:41 Comment(0)
G
11

I finally I found a solution but don't understand why the first approach did not work.

Because you are using the wrong overload of the ReactiveCommand.CreateFromTask method. The delegate user => RootViewModel.DisplayUserProfile(user) may be a Func<CancellationToken, Task> or a Func<IJcUser, Task>. The compiler cannot know which one unless you tell it:

Func<IJcUser, Task> x = user => DisplayUserProfile(user);
UserTouchCommand = ReactiveCommand.CreateFromTask(x);

Or you could be explicit about the type argument:

UserTouchCommand = ReactiveCommand.CreateFromTask<IJcUser>(DisplayUserProfile);
Grote answered 25/1, 2017 at 13:36 Comment(3)
Shouldn't the compiler be able to get this from the Command declaration?Jevons
No. As mentioned, how is it supposed to know that your func is a Func<IJcUser, Task> rather than a Func<CancellationToken, Task> or Func<Something, Task> unless you tell it? It can't.Grote
Very helpful for me to pass a parameter to ReactiveCommond.CreateFromTask. ReactiveUI makes it very confusing here (lots of overloaded types, type deductions, and optional parameters) and always makes me feel desperate.Tours

© 2022 - 2024 — McMap. All rights reserved.