0

I am attempting to make a simple app that enables the user to search for movies using themoviedb api. If I hardcode my search query in the OnAppearing my method, GetAsync works perfectly. However, if I try and take the search term from the user in a SearchBar_TextChanged event handler, GetAsync hangs and never returns. I have searched a few day's for a solution, I assume it has something to do with me mismanaging my await and async calls, or, something to do with the TextChanged event blocking the request. Here is my code, thanks in advance for any solutions/suggestions.

public partial class MovieSearch : ContentPage
{
    private HttpClient _client = new HttpClient();
    private const string URL = "movie?api_key=9d9cb312367f0f2deaa383f9a8fd64d2&query=";//not the full link

    public MovieSearch()
    {

        InitializeComponent();
    }

    async void SearchBar_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
    {
        if (e.NewTextValue == null)
            return;
        if (String.IsNullOrEmpty(e.NewTextValue))
            return;

        var response = await _client.GetAsync(URL + e.NewTextValue);
        var content = await response.Content.ReadAsStringAsync();
        var root = JsonConvert.DeserializeObject<RootObject>(content);
        movieListView.ItemsSource = root.results;
        movieListView.IsVisible = root.results.Any();
        label.IsVisible = !movieListView.IsVisible;
    }
}

1 Answers1

0

you need to use TaskCancellationToken and cancel the request before asking for another one.

Kubaizi
  • 57
  • 1
  • 2