Asım Gündüz
Asım Gündüz

Reputation: 1297

Scroll event is triggered after Task Delay

I'm trying to avoid multiple calls to consume rest service on ListView scroll but it doesn't seem to work..

The problem

When scrolling the ListView, scroll event is triggered continuously, and the rest service is called multiple times.

Approach

I have decided to call the service in a separate thread with 11 seconds of delay

Expectation

After the service is called, the busy property is still set to true for 11 seconds so even if the scroll event is triggered it will not call the service because the busy property is true.

Result

The service is called once but after 11 seconds the scroll event is triggered again and calls the service again.

Edit

I start scrolling, and event is hit multiple times because the event is triggered for every change in scroll-Y value causing to call the service 5 times ( what I want is to call the service 1 time)

for example:

Note that the initial scroll y value is 0. I make a swipe to scroll it. let's say that after the swipe the scroll value is 5 (Event is hit 5 times) there fore my attempt to solve the problem is call the service in a separate thread by using Tasks, but what happens is the event is triggered and runs the task to call the service and because it runs on a different thread it's immediately done with the event ( I mean I get out of the event) and after 11 seconds the event is hit again and so on..

so what happens

what I want is to call the rest service 1 time, not 5 times.

private void Scrollview_Scrolled(object sender, ScrolledEventArgs e)
    {
        Task.Run(async () =>
        {
                if (IsBusy)
                    return;

                 IsBusy = true;
                 await _services.IDealsMService.GetMoreDealsAsync(param1, param2);
                 await Task.Delay(TimeSpan.FromSeconds(11));
         }
     }

Upvotes: 0

Views: 207

Answers (1)

Cfun
Cfun

Reputation: 9721

Try with:

bool IsBusy { get; set; } = false;

private async void Scrollview_Scrolled(object sender, ScrolledEventArgs e)
{
    if (IsBusy)
        return;

    IsBusy = true;
    await _services.IDealsMService.GetMoreDealsAsync(param1, param2);
    await Task.Delay(TimeSpan.FromSeconds(11));     
    IsBusy = false;
}

Upvotes: 1

Related Questions