updateMessage method
Updates the message
in this channel.
Waits for a _messageAttachmentsUploadCompleter
to complete
before actually updating the message.
Implementation
Future<UpdateMessageResponse> updateMessage(
Message message, {
bool skipEnrichUrl = false,
}) async {
_checkInitialized();
final originalMessage = message;
// Cancelling previous completer in case it's called again in the process
// Eg. Updating the message while the previous call is in progress.
_messageAttachmentsUploadCompleter
.remove(message.id)
?.completeError(const StreamChatError('Message cancelled'));
// ignore: parameter_assignments
message = message.copyWith(
state: MessageState.updating,
localUpdatedAt: DateTime.now(),
attachments: message.attachments.map(
(it) {
if (it.uploadState.isSuccess) return it;
return it.copyWith(uploadState: const UploadState.preparing());
},
).toList(),
);
state?.updateMessage(message);
try {
if (message.attachments.any((it) => !it.uploadState.isSuccess)) {
final attachmentsUploadCompleter = Completer<Message>();
_messageAttachmentsUploadCompleter[message.id] =
attachmentsUploadCompleter;
_uploadAttachments(
message.id,
message.attachments.map((it) => it.id),
);
// ignore: parameter_assignments
message = await attachmentsUploadCompleter.future;
}
// Wait for the previous update call to finish. Otherwise, the order of
// messages will not be maintained.
final response = await _updateMessageLock.synchronized(
() => _client.updateMessage(
message,
skipEnrichUrl: skipEnrichUrl,
),
);
final updateMessage = response.message.syncWith(message).copyWith(
// Update the message state to updated.
state: MessageState.updated,
ownReactions: message.ownReactions,
);
state?.updateMessage(updateMessage);
return response;
} catch (e) {
if (e is StreamChatNetworkError) {
if (e.isRetriable) {
state!._retryQueue.add([
message.copyWith(
// Update the message state to failed.
state: MessageState.updatingFailed,
),
]);
} else {
// Reset the message to original state if the update fails and is not
// retriable.
state?.updateMessage(originalMessage.copyWith(
state: MessageState.updatingFailed,
));
}
}
rethrow;
}
}