如何解决在回调结果 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)
})
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。