Home » Android » chat – android channel is updating data multiple times once data is observed-Exceptionshub

chat – android channel is updating data multiple times once data is observed-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a chat activity where I am sending some message on button click, the button is binded with ChatViewModel function like this:

    fun onSendButtonClick(view: View) {

        if (userMsgtext.isEmpty()) {
            return
        }
        Coroutines.main {
            repository.sendTextFromUser(userMsgtext)
            userMsgtext = ""
            val payload: Payload = repository.catchmyMsg()
            println("My Message: $payload")
            val payloadmyMsg = JSONObject(payload)
            val sender = payloadmyMsg.get("sender").toString()
            val msg = payloadmyMsg.get("body").toString()
            val time = payloadmyMsg.get("time").toString()
            val myMsg = Message(sender, msg, time)
            addmsgItem(listOf(myMsg))
        }

    }

Here is the ChatRepository function :

    fun sendTextFromUser(MsgTxt: String) {
        val payload = hashMapOf(
            "body" to MsgTxt
        )
        msg_channel.also {
            it.push("new:msg", payload)
        }.on("new:msg") { message ->
            val payload = JSONObject(message.payload)
            println("PAYLOAD: $payload")

            val sender = payload.get("sender").toString()
            val msg = payload.get("body").toString()
            val time = payload.get("time").toString()

            setmyMsg(message.payload)
            println("*** PAYLOAD *** $sender $msg $time")

        }
    }

It the msg_channel is executing everything 3-4 times once click the send button, how do I fix this thing?

How to&Answers: