在回调结果 RecylerView 后更新 Bind 方法内的 textview

问题描述

我正在开发 Twilio Chat 应用程序,并希望在每个房间回调结果上附加最后一条消息,结果有点延迟,因此我的回收器视图被绘制。

我需要什么: 想在回调结果后更新最后一条消息文本,虽然我使用了 adapter.notifyItemChanges(positon) 但它每次都会更新并从回调中获取 n 个结果(不知道为什么每次调用超过 10 次)时间),并且由于繁重的工作而产生 ANR。下面是我的绑定代码

class ChatThreadVH(
private val binding: SingleMessageThreadItembinding,private val adapter: ChatThreadAdapter,private val channel: Channels) : RecyclerView.ViewHolder(binding.root) {

fun bind(chatThread: Data,position: Int) {
    binding.source = chatThread
    binding.position = position
    binding.adapter = adapter
    getLastMessage(channel,position,binding.source!!)
}


private fun getLastMessage(channel: Channels,position: Int,source: Data) {

    channel.getChannel(
        source.remoteChannelId,ChatCallbackListener<Channel> { channel ->
            channel.messages?.getLastMessages(1,ChatCallbackListener<List<Message>> {
                if (it.isNotEmpty()) {
                    if (it[0].hasMedia()) {
                        binding.tvLastMessage.text = "attachment"
                    } else {
                        binding.tvLastMessage.text = it[0].messageBody
                    }
                }
            })
        })
}

}

因此非常感谢您对此的任何帮助。

谢谢。

解决方法

YourViewModelClass() : ViewModel(),ChatClientListener {
   
   private lateinit var channels: MutableList<Channel>
   val notifyChannelUpdated = MutableLiveData<Int>()

   override fun onChannelUpdated(channel: Channel,p1: Channel.UpdateReason) {
       if(p1 == Channel.UpdateReason.LAST_MESSAGE) {
           val channelPos = channels.indexOfFirst { it.id == channel.id }
           notifyChannelUpdated.postValue(channelPos)
       }
   }
}


Then update your item,becouse there are many reasons why channel may update


class YourActivityOrFragmentClass() : SomeAndroidComponentClass() {
       private lateinit var myAdapter: SomeAdapter
       private lateinit var myViewModel: YourViewModelClass

        override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
            super.onViewCreated(view,savedInstanceState)
            myViewModel.notifyChannelUpdated.observe(viewLifcycleOwner,{ position ->
               myAdapter.notifyItemChanged(position)
            })
        }
   }