-
Notifications
You must be signed in to change notification settings - Fork 1.9k
OnAppearing still called even if I go back from second page #2450
Comments
That's because it's async void. The void method his the await and immediately returns. It's not stopping you from navigating back, but the rest of the code is still executing. |
What should I do if the code is protected override async void OnAppearing()
{
base.OnAppearing();
HttpResponseMessage response = await httpClient.GetAsync("https://github.com/xamarin/Xamarin.Forms");
Debug.WriteLine(response.StatusCode);
} and the |
@5yunus2efendi That's kind of a big question I think reading through the documentation on Tasks would really help you out The short answer is that await is really just a way to help you deal with async code. So what your code above is doing is kicking off a separate background process and then when that process finishes it picks up where it left off. All of this happens within the contained scope of that method. So if you need those results to just be thrown away you would need to deal with that after the await comes back or just cancel the Task when OnDisappearing fires |
Create a Cancellation token OnAppearing and cancel it OnDiappearing. Pass it into your async code. Still smelly and you should look at something like Prism to handle navigation, move your logic to the ViewModel. |
@PureWeen sorry, I didn't mean to ask like that. I actually already implemented the code using cancellation, I just thought there will be a better implementation from XF, anyway, thanks guys! |
@5yunus2efendi aw ok. Here's a discussion about extending Commands in forms to handle tasks Which I think addresses what you're asking about a bit better. |
Description
Suppose I have two pages with NavigationPage, then I override OnAppearing method in the second page:
The weird thing is that, if I navigate from first page to second page and then go back to first page as much as I can before
10000
delay , theDebug.WriteLine("OnAppearing")
code still be called, so am I missing something here?Expected Behavior
The
Debug.WriteLine("OnAppearing")
code not be called even if go back from second pageActual Behavior
The
Debug.WriteLine("OnAppearing")
still be calledBasic Information
Gif how to test
Reproduction Link
App4.zip
The text was updated successfully, but these errors were encountered: