B4J Question How do I pass a result of a sub back to the initial call

Peter Lewis

Active Member
Licensed User
Longtime User
Hi All

I did not know how to write the question as the simple answer is to use Return.

The problem is not that easy.

I have decided to make a Module of code that I would include in all my program that will use MQTT. So simple call to subs will do exactly what i want and as I will be using lots of these around my programs , a better way would be to reuse code.

So the problem I am faced with are the return messages coming in from MQTT Library.

This Sub is not called by me from the module I am working in, however it is triggered from the MQTT Library.

B4X:
Private Sub Client1_MessageArrived (Topic As String, Payload() As Byte)

    Dim PayLoadStr As String
        PayLoadStr = BytesToString(Payload, 0, Payload.Length, "utf8")
       If PayLoadStr.Length = 0 Then
        Return
    End If
    
    Main.ListView1.Items.Add($"${Topic} - ${PayLoadStr}"$)

End Sub

these messages are either triggered by me sending a message or can just arrive at random times. I could transfer the payload automatically to a global variable which I would have to monitor using a timer and if it is not empty , use it and then empty it. But what happens if multiple messages arrive at the same time , then i would lose messages.

Another way I thought would be to add the incoming data to a SQLite database and read off the display off that and possibly empty the database of older messages if required


Is there not a better way to do this ?

Thank you in Advance
 

OliverA

Expert
Licensed User
Longtime User
1) Do nothing. Depending on the volume of messages you receive AND the amount of processing you do in the _MessageArrived event handler, you may not have any issues. I'm pretty sure the MQTT messages are passed along to the event queue of your application and as long as you process the events fast enough, you're OK.
2) If messages at times come in so fast as to overload the event-queue, then you could use a SQLite database to intermediately store your messages and have another routine process the database. Actually, you don't even need a new routine. You could have something like this
B4X:
'Need busy boolean variable declared in globals with False as default value
Private Sub Client1_MessageArrived (topic as string, payload() as byte)
  'put code to store info in database here
  if busy then return ' we're done if we're busy
  busy = True ' we are busy
  'code here to process ALL new information found in the database
  'once done we arrive here
  busy = False
End Sub
 
Upvote 0
Top