缓慢的数据光标模式回调期间数据提示标签不正确

Incorrect datatip label during slow datacursormode callback

添加自定义数据提示相当容易

f = figure();
plot( 1:100, sort(rand(100,1)) );
dc = datacursormode( f );
set( dc, 'UpdateFcn', @onDataCursorUpdate );

function txt = onDataCursorUpdate( tip, evt )
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) )};
end

但更新功能可能需要一段时间才能获取数据提示信息。

在我的例子中,我想包含在 txt 中的数据必须从数据库查询中获取。我意识到从性能的角度来看这是低效的,但它比在内存中存储所有可能的数据提示属性要高效得多!

function txt = onDataCursorUpdate( tip, evt )
    info = mySlowQuery( tip.Position ); % fetch some data about this point
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           sprintf( 'Info: %s', info )};
end

此查询可能需要几分钟(!),不幸的是 MATLAB 在更新标签之前更新了数据提示的位置,因此您可能会得到以下事件序列:

有没有什么办法可以防止这种情况的发生,这样标签不正确就没有期了?

您可以在回调开始时直接与数据提示交互以清除标签,然后 运行 回调主体。输出 txt 仍然自动分配给数据提示 String 属性,但您可以在函数的前面手动更改它:

function txt = onDataCursorUpdate( tip, evt )
    % Clear the string first, use "loading..." as placeholder text
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           'Info: loading...'};
    tip.String = txt;
    % Now run the slow update
    info = mySlowQuery( tip.Position ); % fetch some data about this point
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           sprintf( 'Info: %s', info )};
end