Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
How best to coordinate with a background thread/process?
-
I'm working on a pythonista project which displays a UI for the user to interact with, but also needs to run background network I/O which will receive data that causes updates to the UI.
So, since I haven't done anything like that in pythonista before, I was wondering how people approach it? Assuming the network I/O is running in the background via threads, or multiprocessing, or some other asynchronous system, and is using some kind of message queue to receive and provide data to the UI, how should I update the UI as needed?
Is this something that in_background() would be good for? I was hoping that there was some way to schedule a function to be called in the UI thread event loop which would look for incoming messages and respond. I assume I can't simply call into the UI thread from some other python thread which is running and monitoring the message queue?
I'm still very new to pythonista, and my understanding of its thread interaction model is not very strong, so any advice or examples would be appreciated, thanks.
-
@shinyformica very quick and dirty sample, the thread can access to ui objects if it knows the view
import ui import threading import time from datetime import datetime class my_thread(threading.Thread): def __init__(self,my_view): threading.Thread.__init__(self) self.my_view = my_view def run(self): n = 0 while n < 10: self.my_view['label'].text = str(datetime.now()) time.sleep(0.5) n = n + 1 v = ui.View() v.name ='test' l = ui.Label(name='label') l.frame = (10,0,290,32) l.text ='not started' v.add_subview(l) b = ui.Button() b.frame = (10,50,100,32) b.title = 'start' b.border_width = 1 b.background_color = 'white' def a(sender): thread = my_thread(sender.superview) thread.start() b.action = a v.add_subview(b) v.frame =(0,0,300,300) v.present('sheet')