Hello,
I tried o call it it the constructor, but my app frezes
You cannot call await/async method in the constructor
You can refer to The Asynchronous Initialization Pattern.
- Create a
IAsyncInitialization
interface public interface IAsyncInitialization
{
Task InitializeAsync();
}- Then implement this interface and initialize this
InitializeAsync()
in yourMainPageViewModel
constructor(Note: do not forget to addpublic Task Initialization { get; private set; }
). public partial class MainPageViewModel : ObservableObject, IAsyncInitialization
{
readonly IGetWord getWord;
string answer = string.Empty;
// I add characters for tesing.
readonly List<char> charList = new() { 'j', 'a', 'c' }; [ObservableProperty]
private string _spotlight; public MainPageViewModel(IGetWord getWord)
{
this.getWord = getWord;
//initialize thisInitializeAsync()
Initialization = InitializeAsync(); }
public Task Initialization { get; private set; } private void CalculateWord(string ans, List<char> guessed)
{
var temp = ans.Select(x => guessed.IndexOf(x) >= 0 ? x : '_').ToArray();
Spotlight = string.Join(' ', temp);
}
private async Task<string> GetWord()
{
answer = await getWord.DownloadRandomWordAsync();
return answer;
}
public async Task InitializeAsync()
{
answer = await GetWord();
CalculateWord(answer, charList);
}
}
- Then implement this interface and initialize this
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.