我正在开发一个具有 MVVM 架构的聊天应用程序,我SharedFlow
用来将传入的消息Repository
从ViewModel
. 当用户离线,另一个用户向他发送大量消息时,用户一上线,消息就会接踵而至,Repository
需要传送到ViewModel
用户界面中显示。我首先将extraBufferCapacity
值设置为 1,然后看到在这种情况下,只有前两条消息在ViewModel
. 然后我将extraBufferCapacity
值增加到 6 并看到前 7 条消息被传输到ViewModel
. 现在如果我将extraBufferCapacity
值增加到Int.MAX_VALUE
,会导致内存泄漏吗?
存储库:
object ChatRepo {
private val _receiveMessageFlow = MutableSharedFlow<Message>(extraBufferCapacity = Int.MAX_VALUE)
val receiveMessageFlow = _receiveMessageFlow.asSharedFlow()
fun listen(socket: Socket) {
socket.on(Config.ON_PV_MESSAGE, onPvMessage)
}
private val onPvMessage = Emitter.Listener { args ->
val message = Gson().fromJson(args[0].toString(), Message::class.java)
_receiveMessageFlow.tryEmit(message)
}
}
视图模型:
class ChatViewModel(var receiver: User) : ViewModel() {
private val _messagesLive = MutableLiveData<Resource<MessageList>>()
val messagesLive = _messagesLive as LiveData<Resource<MessageList>>
init {
observeReceivedMessage()
}
private fun observeReceivedMessage() {
viewModelScope.launch {
ChatRepo.receiveMessageFlow.collect { message ->
if (message.senderUid == receiver.uid) {
addMessage(message)
}
}
}
}
private fun addMessage(message: Message) {
val resource = _messagesLive.value ?: Resource.success(MessageList())
val messageList = resource.data ?: MessageList()
messageList.addMessageLast(message)
_messagesLive.value = Resource.add(messageList, 0)
}
}