0

To be more specific, I want to store the last 20 messages in an array for later use.

I am working on the example code here.

I was going to build a global variable and store MSG. Payload() in it. But I found that the main function is only executed once in the whole process of running the program. Do I need to write all my logic in MQTT.MessageHandler?

I'm really confused, thanks for your help.

3
  • 1
    The examples show you how to wait for a signal before exiting. Incoming messages will trigger a call to your callback; how you handle these is up to you (update a global slice, push messages to a channel etc). It will be easier to assist you if you make an attempt at this and show us your code along with a description of what is not working.
    – Brits
    May 18, 2021 at 6:44
  • I have applied the exit signal, and it works very well. From your example, my understanding is: the main function is executed only once and does not process messages; If I need to do anything with the message, I have to write some new handlers. Is my understanding correct? Here is my code. May 18, 2021 at 9:29
  • Please edit the question and add your code (links may break in the future). As per the language spec "Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete" (so yes, main is only executed once). When a message arrives the handler will be called; this happens in a goroutine - if you are new to go working through the tour might help.
    – Brits
    May 18, 2021 at 9:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.