Fix some events getting dispatched twice when double newline is missing at the end#44
Merged
wojciechkrol merged 1 commit intobinaryminds:masterfrom Feb 23, 2024
Conversation
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
As surfaced in #42, react-native-sse currently dispatches the same event twice when there is no extra newline at the end of the response text. For example, here is what currently happens for a given response text:
response text #1:
data: MESSAGE ONE\n\ndata: MESSAGE TWO\n<-- note that there is only one\nhereresults in parsed lines
[ "data: MESSAGE ONE", "", "data: MESSAGE TWO", "" ]so the events "MESSAGE ONE" and "MESSAGE TWO" both get dispatched, and
lastIndexProcessedis set to the index of the double newline\n\nwhich is 19. However, the actual length of the response text is 37.response text #2:
data: MESSAGE ONE\n\ndata: MESSAGE TWO\n\ndata: MESSAGE THREE\n\ndata: MESSAGE FOUR\nstarting at index 19, this gives parsed lines
[ "data: MESSAGE TWO", "", "data: MESSAGE THREE", "", "data: MESSAGE FOUR", "" ]so the event "MESSAGE TWO" gets dispatched again, "MESSAGE THREE" and "MESSAGE FOUR" also get dispatched, and
lastIndexProcessedis set to 59. However, the actual length of the response text is 78.And it continues like this... always dispatching the last event from the previous chunk twice.
This PR fixes that problem. My solution is inspired by #39 by @GidoHakvoort, but it avoids some shortcomings and problems of that implementation.
With these changes, react-native-sse will now always only look at the chunk of the response from the
lastIndexProcessedtill the last double newline found in the response text. Afterwards it setslastIndexProcessedto the index of that double newline, so the next iteration starts there, and so on.Fixes #42.
Closes #39.