Blocking function awaiting response from widget #678
-
Running in a notebook pyhton kernel, is there a pattern for a blocking wait on a response from the widget js? import threading
from anywidget import AnyWidget
from traitlets import Unicode, observe
from IPython.display import display
class BlockingMessageWidget(AnyWidget):
message = Unicode('').tag(sync=True)
reply = Unicode('').tag(sync=True)
def __init__(self):
super().__init__()
def sendMessage(self, msg):
self.reply = ''
self.message = msg
def blocking_reply(self, timeout=None):
# something
return self.reply
async def await_blocking_reply(self, timeout=None):
# something
return self.reply
_esm = """
export function render({ model, el }) {
const processMessage = (msg) => {
// Simulate some processing
return new Promise(resolve => {
setTimeout(() => {
resolve(`Processed: ${msg}`);
}, 2000);
});
};
model.on('change:message', async () => {
const msg = model.get('message');
if (msg) {
const reply = await processMessage(msg);
model.set('reply', reply);
model.save_changes();
}
});
el.textContent = 'Blocking Message Widget';
}
""" and then:
And either:
or:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I was surprised by how tricky this is. There are libraries like Some relevant discussion and links can be found in this ipywidgets issue: jupyter-widgets/ipywidgets#3039 |
Beta Was this translation helpful? Give feedback.
Ah, thanks for that.
The
jupyter_ui_poll
approach appears to work in a jupyter served browser environment: