-
I have dataclasses that periodically receive information (from a USB device) and update the class's variables when that happens. The updater runs in its own thread. I can modify the dataclass to make all its variables How can I attach these variables to reactive UI? My first attempt was to create a wrapper "display" class that watches the data class, but my UI never updates: class UsbData(DOMNode):
var = reactive(0)
test = UsbData()
def test_thread():
global test
while True:
test.var += 1
time.sleep(0.1)
Thread(target=test_thread, daemon=True).start()
class Display(Widget):
val = reactive("not yet set")
def __init__(self, data_class, **kwargs):
super().__init__(**kwargs)
def update(val: int):
self.val = val
self.watch(data_class, "var", update)
def render(self):
return f"{self.val}"
# and then use Display(test) as a widget in my App If bind a keystroke to perform |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
I think you'll find that reactives are designed to be used as part of widgets mounted in the DOM. If you are wanting to move data from a thread and into your app it's likely better to do that by posting messages. You may also want to read up on Textual's threaded workers. |
Beta Was this translation helpful? Give feedback.
Alright, I think I've come to a solution I'm happy with.
Some more context for you, hopefully helps explain why I chose this - I have a schema for telemetry being sent back by one or more devices I've attached to my PC. Stuff like temperature, volts, amps, etc. Using that schema, I auto-generate the deserialisation code and shove it into dataclasses. The use of this data might be spread over several screens in my app, so I can't embed the data into a Widget using my code-gen.
My initial implementation was a Rich
Live
that updated at 10Hz, redrawing the screen each time at a CPU cost of about 5-8%. Works great, but I didn't like the expense.I experimented a bit with message passing, but i…