'How to 'cancel' the stream data response after request another one

I have a list of Expandable Items, each time I click in one of the items a stream is called returning a list of another items related to that I clicked on. The problem is if I quick expand two items of my initial list, the last remains with the items from the first one.

Example of what is expected:

(EXPANDABLE LIST)
Colombia
   (items showed when I click on Colombia)
   Bogotá
China
   (items showed when I click on China)
   Beijing

Example of what happens if I quickly open two items:

(EXPANDABLE LIST)
Colombia (clicked first, and before the load quickly click on China)
China
   Bogotá

Is there a way to close or cancel or pause the stream every time I expand one item?

UPDATE SCREEN

return ExpansionTile(
              leading: items[index].image == null || items[index].image.isEmpty ? Image.asset(ASSET_NOIMAGE_URL,
                  fit: BoxFit.scaleDown
              ) : Image.network('${BASE_ROUTE_URL}/${ROUTE_SLASH}/${items[index].image}', fit: BoxFit.scaleDown,),
              title: Text('${items[index].code}  |  ${items[index].desc}', style: TextStyle(fontWeight: FontWeight.bold, color: AppColorSecondary),),
              children: [
                Container(
                  height: MediaQuery.of(context).size.height * 0.75,
                  width: MediaQuery.of(context).size.width,
                  child: CountryDetails(items[index]),
                ),
              ],

WIDGET

class _CountryDetailsState extends State<CountryDetails> {
  Country country;

  @override
  void initState() {
    country = Provider.of<Country>(context, listen: false);

    country.load(produtoGradeFVList: Provider.of<CountryListProvider>(context, listen: false).produtoGradeFVList).then((value) {
      
    }); // here the stream is feed

    super.initState();
  }


Solution 1:[1]

You could set a debounce duration on the stream controller to avoid receiving two requests within a very short interval of time as:

_cityController.stream
  .debounceTime(const Duration(milliseconds: 500))
  .listen(_handlerFunctionForTapEvent);

Here, _cityController is your StreamController that's listening to the tap events of expandable items from the ui. Try setting a debounce time of 500 milliseconds, hopefully that would fix the issue.

Or you could also send the name of country along with the list of cities in the response from the stream and perform a check in the ui before displaying the city names in the expandable list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suvash Bhandari