Search Unity

ListView bindItem with asynchronous operations

Discussion in 'UI Toolkit' started by MaskedMouse, Jun 11, 2020.

  1. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    I'm wondering, when you have a ListView and have items with data that require some more processing, let's say an extra texture (image) downloaded from web. Using an async await plugin.

    So code looking something like this (Pseudo code):
    Code (CSharp):
    1. private async void BindItem(VisualElement element, int index)
    2. {
    3.     var data = Source[index];
    4.     var imageTexture = await DownloadTexture(data.ImageUrl);
    5.     element.Q<Image>("Image Texture").image = imageTexture;
    6. }
    When a refresh happens quickly in succession, DownloadTexture might not be done yet. But refresh is binding all items again. This could possibly cause an overwrite of an old texture download.

    How would you go around this asynchronous loading problem considering the ListView binding is synchronous?

    Things I thought about but not sure of
    - I could make extra safeguards to check whether the downloaded texture is still the texture that should be set.
    - Store the Task in a separate List, check before downloading if the task is null -> download item, if != null cancel the task somehow using a Cancellation Token.
     
    squigglebucket likes this.
  2. uMathieu

    uMathieu

    Unity Technologies

    Joined:
    Jun 6, 2017
    Posts:
    398
    Cancel the task in UnbindItem?
     
    squigglebucket likes this.
  3. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    squigglebucket likes this.
  4. uMathieu

    uMathieu

    Unity Technologies

    Joined:
    Jun 6, 2017
    Posts:
    398
    Last edited: Jun 12, 2020
    squigglebucket and MaskedMouse like this.