I am working on a chat application with MVVM architecture and I use SharedFlow to transfer incoming messages from Repository to ViewModel. When the user is offline and another user sends a large number of messages to him, as soon as the user is online, the messages are received one after the other in the Repository and need to be transferred to the ViewModel for display in the user interface. I first set the extraBufferCapacity value to 1 and saw that in this case only the first two messages are received in the ViewModel. Then I increased the extraBufferCapacity value to 6 and saw that the first 7 messages were transmitted to the ViewModel. Now if I increase the extraBufferCapacity value to the Int.MAX_VALUE, will it cause memory leak?
Repository:
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)
}
}
ViewModel:
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)
}
}