Client using Kotlin

I’ve successfully connected and sent mqtt messages to mosquitto broker and using current Kotlin on Android Studio. Since I’m pretty new to andriod programming i got stuck in the subscribe callback part of the mqtt client and can’t find any examples that could boost my knowledge.
// Setup MQTT Client
val client: Mqtt3BlockingClient = Mqtt3Client.builder()
.identifier(“uuid_would_be_better”)
.serverHost(“192.168.137.102”)
.serverPort(1883)
.buildBlocking()

// Connect with MQTT Client
try {
val connAckMessage = client.connectWith()
.simpleAuth()
.username(“sensor01”)
.password("******".toByteArray())
.applySimpleAuth()
.willPublish()
.topic(“sensor01/stat”)
.qos(MqttQos.AT_LEAST_ONCE)
.payload(“off”.toByteArray())
.retain(true)
.applyWillPublish()
.send()
Toast.makeText(applicationContext, connAckMessage.toString(), Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, “Kotlin Fehler beim Senden”, Toast.LENGTH_LONG)
.show()
} catch (e: java.lang.Exception) {
Toast.makeText(applicationContext, “Java Fehler beim Senden”, Toast.LENGTH_LONG).show()
}

var counter:int = 16

client.publishWith().topic(“sensor01/counter”).qos(MqttQos.AT_LEAST_ONCE).payload(counter.toString().toByteArray()).send()

All works fine up to here.

But i can’t really find out how to implement the callback.
client.toAsync().subscribeWith()
.topicFilter(“test/topic”)
.qos(MqttQos.AT_LEAST_ONCE)
.callback(System.out::println)
.send()

works fine, gets compiled and gives the expected results. I’m just stuck on how to get hold of the subscibed Payload instead of just printing it to debug output…

any help that points me into the right direction would be appreciated!

You almost done it! Here:

client.toAsync().subscribeWith()
.topicFilter(“test/topic”)
.qos(MqttQos.AT_LEAST_ONCE)
.callback(System.out::println)
.send()

you use function “callback”, that need a “Consumer” function. In other word, a function that perform any action you need but it returns nothing.
To this function is automatically passed an object of type “Mqtt3Publish”, that I suppose is the all message that a device created when it published it.

If you strictly need to save this obj to use it in other part of code, try this:
var lastRes : Mqtt3Publish
client.toAsync().subscribeWith()
.topicFilter(“ciao2”)
.qos(MqttQos.AT_LEAST_ONCE)
.callback { actResponse → lastres = actResponse}
.send()

(in kotlin language, if i try to write it in java it should be:
Mqtt3Publish lastRes;
client.toAsync().subscribeWith()
.topicFilter(“ciao2”)
.qos(MqttQos.AT_LEAST_ONCE)
.callback ( actResponse → lastres = actResponse )
.send()
)

Thank you for your question, it speed up my learning about interaction between Android and MQTT devices!!
I hope this help you (despite of the years of delay, but i started this project last month!), happy coding!!