Adding State to the Update Notification Pattern, Part 5 -- Raymond Chen

RaymondChen_5in-150x150.jpgManaging stateful notifications is challenging when multiple requests arrive, and the goal is to only notify about the latest one. In the EditControl class, we use a counter to track the most recent request, updating it on the UI thread to ensure accurate ordering and prevent stale data from being processed. This approach works but is inefficient due to redundant calculations. Next time, we'll refine this strategy for greater efficiency.

Adding State to the Update Notification Pattern, Part 5 

by Raymond Chen

From the article:

We’ve been looking at the problem of a stateful but coalescing update notification, where multiple requests for work can arrive, and your only requirement is that you send a notification for the last one.

This time, we’ll apply the trick of using a counter to record who is doing the work on behalf of the most recent change. Here’s our first attempt:

 
class EditControl
{
    ⟦ ... existing class members ... ⟧

    unsigned m_latestId;
};

winrt::fire_and_forget
EditControl::TextChanged(std::string text)
{
    auto lifetime = get_strong();

    co_await winrt::resume_background();

    auto id = ++m_latestId;

    std::vector<std::string> matches;
    for (auto&& candidate : FindCandidates(text)) {
        if (candidate.Verify()) {
            matches.push_back(candidate.Text());
        }
    }

    co_await winrt::resume_foreground(Dispatcher());

    if (id != m_latestId) co_return;

    SetAutocomplete(matches);
}

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.