0

I am trying to create a MVVM Avalonia app using the ReactiveUi and want to execute a command async in order to keep the user interface working. However this is not the case. After hitting my button, the ui freezes until the command has finished executing even though i am running it async.

Does somebody know, what i am doing wrong here?

This is what i am currently doing:

ViewModel:

public LoginViewModel()
{
    TryConnectAsyncCommand = ReactiveCommand.CreateFromTask(TryConnectAndLogin);
}

public ReactiveCommand<Unit, Unit> TryConnectAsyncCommand { get; }

async Task TryConnectAndLogin()
{
    ErrorFlag = false;
    ClientConversationManager.TryConnect(EnteredInstance, EnteredPort);
    if (ClientConversationManager.IsConnected)
    {
            
    }
    else
    {
        ErrorFlagContent = "Could not connect to server :/";
        ErrorFlag = true;
    }
}

View:

Command="{Binding TryConnectAsyncCommand}"
4
  • There are no awaits in your function. Perhaps there should be something like await ClientConversationManager.TryConnectAsync( or similar Commented Jun 4, 2023 at 11:04
  • Making the other functions async and awaiting them sadly does not solve my problem. Also why can't i just await the entire TryConnectAndLogin? Commented Jun 4, 2023 at 11:06
  • No it will block the thread unless you have an await. Marking it async doesn't magically do anything until you have an await Commented Jun 4, 2023 at 11:08
  • So i awaited the other functions but it sadly did not solve my problem Commented Jun 4, 2023 at 11:15

1 Answer 1

1

Your method TryConnectAndLogin is synchronized. You can make it async using Task.Run (standard way) or Observable.Start (rx way).

public LoginViewModel()
{
    TryConnectAsyncCommand = ReactiveCommand.CreateFromObservable(TryConnectAndLogin);
}

public ReactiveCommand<Unit, Unit> TryConnectAsyncCommand { get; }

private IObservable<Unit> TryConnectAndLogin()
{
    return Observable.Start(() =>
    {
        ErrorFlag = false;
        ClientConversationManager.TryConnect(EnteredInstance, EnteredPort);
        if (ClientConversationManager.IsConnected)
        {
                
        }
        else
        {
            ErrorFlagContent = "Could not connect to server :/";
            ErrorFlag = true;
        }
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.