I have found a solution and answer to my own question:
To avoid an infinitive loop, I used the throttle function during registration.
function makeListener() {
let prevBlockId;
return function updateBlockMode() {
const currentSelectedBlock = wp.data.select('core/block-editor').getSelectedBlock();
const currentBlockId = (currentSelectedBlock) ? currentSelectedBlock.clientId : null;
if (currentBlockId === prevBlockId) {
wp.data.dispatch('core/block-editor').updateBlockAttributes(currentBlockId, { mode: 'edit' });
} else {
wp.data.dispatch('core/block-editor').updateBlockAttributes(prevBlockId, { mode: 'preview' });
}
prevBlockId = currentBlockId;
};
};
const unsubscribe = wp.data.subscribe(_.throttle((makeListener()), 200));
This approach works for me but maybe there is a better solution. I would appreciate any ideas and suggestions.