SSEparser | R Documentation |
This class can help you parse a single server sent event or a stream of them.
You can inherit the class for a custom application.
The parse_sse()
function wraps this class for a more functional approach.
The HTML specification
tells us that event streams are composed by chunks (also called blocks, or messages) and lines.
A single new line character (\n
) states the end of a line, and two consecutive new line characters (\n\n
) state the end of a chunk.
This means that, in practice, an event can be composed of one or more chunks, and a chunk can be composed of one or more lines.
data: This is the first chunk, it has one line data: This is the second chunk extra: It has two lines data: This is the third chunk, it has an id field. This is common. id: 123 : Lines that start with a colon are comments, they will be ignored data: This is the forth chunk, it has a comment data: This is the fifth chunk. Normally you will receive a data field custom: But the server can send custom field names. SSEparser parses them too.
Typically, an event stream will send a single chunk for event, but it is important
to understand that event != chunk because SSEparser$events
will be a list of
all the chunks received as it makes a more consistent output.
An object with R6 class SSEparser
events
List that contains all the events parsed. When the class is initialized, is just an empty list.
append_parsed_sse()
Takes a parsed event and appends it to the events
field. You can overwrite this method if you decide to extend this class.
SSEparser$append_parsed_sse(parsed_event)
parsed_event
Event to append to the events
field.
parse_sse()
Takes a string that comes from a server sent event and parses it to an R list. You should never overwrite this method.
SSEparser$parse_sse(event)
event
A length 1 string containing a server sent event as specified in the HTML spec.
new()
Create a new SSE parser
SSEparser$new()
clone()
The objects of this class are cloneable with this method.
SSEparser$clone(deep = FALSE)
deep
Whether to make a deep clone.
example_event <-
"data: This is the first chunk, it has one line
data: This is the second chunk
extra: It has two lines
data: This is the third chunk, it has an id field. This is common.
id: 123
: Lines that start with a colon are comments, they will be ignored
data: This is the fourth chunk, it has a comment
data: This is the fifth chunk. Normally you will receive a data field
custom: But the server can send custom field names. SSEparser parses them too."
parser <- SSEparser$new()
parser$parse_sse(example_event)
str(parser$events)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.