Xamarin forms what is the best of search query with API

79 Views Asked by At

I am learning xamarin forms. I using Azure search API to query news but sometimes the result of search is not good because of my search code. I can tap for instance "cat" but because of the delay "ca" is sent to the API.

What I woud like please :

I would like to launch automatically my search function each time the user is not tapping on search bar.

For instance lets say a user is willing to tap "tennis is a sport":

So he taps quikly on search bar and make a pause on "tennis is" => launch function on "tennis is"

Then he continues and finishs the sentence : "tennis is a sport" => launch function on "tennis is a sport"

If there is a better way of doing it, I will take.

Here is my code :

Task tasksearch = null;
int timeDelaySearch = 1000;

void OnSearcMyNews(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
{


    try {

        if (tasksearch == null || tasksearch.IsCompleted)
        {
            tasksearch = Task.Run(async () =>
                {
                    await Task.Delay(timeDelaySearch);



                    Device.BeginInvokeOnMainThread( () =>
                    {
                   

                        searchTerm = searchTerm.ToLower();
                        _ = SearchNewsDataAsync(searchTerm, UserConnected.NewsLanguage);
                        tasksearch = null;

                    });



            });
        }



    }
    catch (Exception ex)
    {
        
    }




}

Update 26 Feb: I have tried this but still do not work correctly. if I would like to type "working" sometimes I get search for "workin".

New code :

   int _countSeconds = 0;
    void OnSearcMyNews(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
    {
    
    
    try {
    
          
        _countSeconds = 0; // if user type again the function is Initialize
        Device.StartTimer(TimeSpan.FromMilliseconds(1000), () =>
        {
        // count == 2 to wait a little bit before searching
        if (_countSeconds == 2)
        {
            _ = Task.Run(async () => {
    
                await Device.InvokeOnMainThreadAsync(async () =>
                {
    
                     GetNewsAPIDataAsync();
    
                });
    
            });
    
    
            return false;
        }
    
       
        _countSeconds = _countSeconds + 1;
        return true;
        });
             
    
    
    
    }
    catch (Exception ex)
    {
        
    }
    
    }
0

There are 0 best solutions below