title: Solution for continuously running a code part within a MQTT client?
body: <p>I am trying to send me a message over a mqtt connection and then perform a task on the received messages which are collected in the inbox. The problem is that when I run the code, the messages have not been received yet and the part in the code which shall work on the information in the messages does not run again.</p>
  
  <p>I thought about using a <code>while True:</code> loop for that bit, but then the mqtt script won't be reached at all. This does not work. </p>
  
  <p>This might be a very fundamental question, but how can I achieve running the mqtt client continuously and deal with the collected messages at some point later on?</p>
  
  <pre><code>import paho.mqtt.client as client
  
  hostname = 'test.mosquitto.org'
  topic = "personal/topic"
  
  # receiving the data
  inbox = []    
  
  def on_message(client, userdata, msg):
      msg = msg.payload.decode()
      inbox.append(msg)
      print("Received Message No. %s:    %s" % (len(inbox), msg))    
  
  def on_connect(client, userdata, flags, rc):
      print("Connection returned result: " + str(rc))
      client.subscribe(topic)
  
  # this is where I want to perform a task on the message
  y = []
  X = []
  for msg in inbox:
      label, data = msg.split(': ')
      data = data.split(', ')
      y.append(label)
      X.append(data)
  
  # the mqtt part
  client = client.Client()
  client.on_message = on_message
  client.on_connect = on_connect
  client.connect(hostname)
  client.loop_forever()
  </code></pre>
  
  <p>This is the construction using <code>client.loop_start()</code>at the end of the script (related to @hardillb's answer):</p>
  
  <pre><code># the mqtt part
  client = client.Client()
  client.on_message = on_message
  client.on_connect = on_connect
  client.connect(hostname)
  client.loop_start()
  
  while True:
      y = []
      X = []
      for msg in inbox:
          label, data = msg.split(': ')
          data = data.split(', ')
          y.append(label)
          X.append(data)
  
  client.disconnect()
  client.loop_stop()
  </code></pre>