Within an Event, creators or automations will be publishing Elements – bi-directional content units that have certain properties and behaviours built in, as defined in the App Spec. In general, there are two types of Elements:
Interactive Elements: those that are bi-directional in nature and allow your users to interact with the content. For example by providing live results and seeing how other people have responded. You might choose to define an interactive Element to behave like a poll, containing a question, a number of possible answer options and a duration.
One-way Elements: those that are broadcast to all, but do not require a response. For example an information unit, like a message, promotion or image gallery.
An Event may include multiple Elements. For example if you create an Event for a soccer game, an Element might be a result prediction appearing before the game starts and another that triggers whenever a goal is scored.
Interaction is the purpose of the platform, but we'll start with simpler one-way Elements.
One-way Elements
Let's look at how to use non-interactive One-way Elements in your application.
The snippet below retrieves the array of Elements already existing within the Event and illustrates how you can use its contentType to differentiate each Element type. In the example, we determine a single type of Element being received - goalScored.
asyncfunctiondisplayElements(event) {try {constelements=awaitgetElements(event);for (constelementof elements) {switch (element.contentType) {case'goalScored':displayGoalScored(element);break; } } } catch (e) {console.error('Something went wrong!', e); }}functiondisplayGoalScored(element) {// In this function we know the element is a goal scored, so we can // equally make some assumptions about what data will be available.// As you can see below, given the control you have over the App // Spec, you can provide via Studio as much data as you want to support,// in this example the goal scorer name, number, and the amount of goals// they scored today, so you can add some extra fanfare// in your UI when they score a hat trick!const { fields: {goalScorerName,goalScorerNumber,goalScorerGoalsToday, }, } = element// Draw the UI based on your UI framework.}
funcdisplayElements(inevent: Event) { event.getElements { [weak self] result inguardlet self = self else { return }do {let elements =try result.get() elements.forEach { element inswitch element.contentType {case"goalScored": self.displayGoalScored(element)default:// Element type not recognised.return } } } catch {// Treat the error } }}funcdisplayGoalScored(_element: Element) {// In this function we know the element is a goal scored, so we can // equally make some assumptions about what data will be available.// As you can see below, given the control you have over the App // Spec, you can provide via Studio as much data as you want to support,// in this example the goal scorer name, number, and the amount of goals// they scored today, so you can add some extra fanfare// in your UI when they score a hat trick!let goalScorerName = element.fields["goalScorerName"]let goalScorerNumber = element.fields["goalScorerNumber"]let goalScorerGoalsToday = element.fields["goalScorerGoalsToday"]// Draw the UI based on your UI framework.}
fundisplayElements(event: Event) { event.getElements { it.onFailure {// Treat the error, `it` is a throwable } it.onSuccess { it.forEach { element ->when (element.contentType) {"goalScored"->displayGoalScored(element)else-> {// element type not recognised } } } } }}fundisplayGoalScored(element: Element) {// In this function we know the element is a goal scored, so we can // equally make some assumptions about what data will be available.// As you can see below, given the control you have over the App // Spec, you can provide via Studio as much data as you want to support,// in this example the goal scorer name, number, and the amount of goals// they scored today, so you can add some extra fanfare// in your UI when they score a hat trick!val goalScorerName = element.fields["goalScorerName"]val goalScorerNumber = element.fields["goalScorerNumber"]val goalScorerGoalsToday = element.fields["goalScorerGoalsToday"]// Draw the UI based on your UI framework.}
getElements will return a list of elements sorted so that the most recent element is first, and the oldest is last.
Additionally, you can subscribe to updates to a given Element using the following snippet:
// Called when the results of an interactive element changeconstunsubscribeOnElementResults=onElementResults( element, (results) => { console.log(results) });// Called when the element is updatedconstunsubscribeOnElementUpdated=onElementUpdated( element, () => { console.log(element) });// Called when the state of the element is updatedconstunsubscribeOnElementStateChanged=onElementStateChanged( element, () => { console.log(element) });
Interactive Elements
Interactive Elements get fans involved and make your experiences more rewarding. They have the following properties which differ from One-way Elements:
State: open or closed state, where open means the user can still interact with the Element. The timespan where the user can vote can be obtained through the duration property.
Question and AnswerOptions: The Element usually will have a question associated with it for the user to answer by interacting with some potential answers. Through the App Spec you can specify what data is included in either the Question and AnswerOptions. This enables you to create rich questions and answers which could include videos, images, links to other content on your application, ...
Results: Results bring a sense of belonging into your users interaction, by letting your users know how their peers are answering a question. You will receive these values both as a total vote count as well as a percentage of the total votes.
The snippet below updates the previous one to add a new type of element, a poll:
funcdisplayElements(inevent: Event) { event.getElements { [weak self] result inguardlet self = self else { return }do {let elements =try result.get() elements.forEach { element inswitch element.contentType {case"poll": self.displayPoll(element)case"goalScored": self.displayGoalScored(element)default:// Element type not recognised.return } } } catch {// Treat the error } }}funcdisplayPoll(_element: Element) {let question = element.question!["text"]let questionImageURL = element.question!["imageURL"]let answers = element.answerOptions!.map { answerOption inreturn answerOption["text"]as!String }let pollCustomField = element.fields["poll custom field"]let state = element.state// Draw the poll}
fundisplayElements(event: Event) { event.getElements { it.onFailure {// Treat the error, `it` is a throwable } it.onSuccess { it.forEach { element ->when (element.contentType) {"poll"->displayPoll(element)"goalScored"->displayGoalScored(element)else-> {// element type not recognised } } } } }}fundisplayPoll(element: Element) {val question = element.question!!["text"]val questionImageURL = element.question!!["imageURL"]val answers = element.answerOptions!!.map { it["text"] }val pollCustomField = element.fields["poll custom field"]val state = element.state;// Draw the poll}
Responding to an Interactive Element
Once you have displayed the answer options on screen, submit the user's answer using the answer()method.
In the snippet below we show how an answer can be submitted, alongside its error handling so you can contextualise to the user if anything goes wrong. We assume that the variable userAnswer contains the 0-based index of the answer option selected by the user.
functionsendAnswer(element, index) {try {// index should be e.g. 0 to the count of options available - 1answer(element, index);// Your answer was sent successfully } catch {if (e instanceofMonterosaError) {switch (e.code) {caseAnswerError.OptionIndexOutOfRange:// The index is outside the range of possible optionsbreak;caseAnswerError.AboveMaxVoteOptions:// You voted for more indexes than is allowedbreak;caseAnswerError.BelowMinVoteOptions:// You voted for fewer indexes than is allowedbreak;caseAnswerError.AboveMaxVotesPerUser:// You voted with a higher total value than is allowedbreak;caseAnswerError.AboveMaxVotesPerOption:// You voted with a higher value than is allowed in a single optionbreak;caseAnswerError.VotedOnNonInteractiveElement:// You tried to vote on a non interactive elementbreak;caseAnswerError.VotedOnClosedElement:// You voted on closed elementbreak;default:// Shouldn't occur, but be ready for it as more cases could be added in the future.break; } } else {// Shouldn't occur } }}
funcanswer(element: Element, withindex: Int) {do {try element.answer(with: index)// Your answer was sent successfully }catchlet err asElement.AnswerError where err == .optionIndexOutOfRange {// The index is outside the range of possible options }catchlet err asElement.AnswerError where err == .aboveMaxVoteOptions {// You voted for more indexes than is allowed }catchlet err asElement.AnswerError where err == .belowMinVoteOptions {// You voted for fewer indexes than is allowed }catchlet err asElement.AnswerError where err == .aboveMaxVotesPerUser {// You voted with a higher total value than is allowed }catchlet err asElement.AnswerError where err == .aboveMaxVotesPerOption {// You voted with a higher value than is allowed in a single option }catchlet err asElement.AnswerError where err == .votedOnNonInteractiveElement {// You tried to vote on a non interactive element }catchlet err asElement.AnswerError where err == .votedOnClosedElement {// You voted on closed element }catch {// Shouldn't occur }}
funanswer(element: Element, index: Int) {try { element.answer(index)// Your answer was sent successfully } catch (e: ElementVoteError){when (e.errorType) { ErrorType.OPTION_INDEX_OUT_OF_RANGE ->// The index is outside the range of possible options ErrorType.ABOVE_MAX_VOTE_OPTIONS ->// You voted for more indexes than is allowed ErrorType.BELOW_MIN_VOTE_OPTIONS ->// You voted for fewer indexes than is allowed ErrorType.ABOVE_MAX_VOTES_PER_USER ->// You voted with a higher total value than is allowed ErrorType.ABOVE_MAX_VOTES_PER_OPTION ->// You voted with a higher value than is allowed in a single option ErrorType.VOTED_ON_NON_INTERACTIVE_ELEMENT ->// You tried to vote on a non interactive element ErrorType.VOTED_ON_CLOSED_ELEMENT ->// You voted on closed elementelse-> {// Shouldn't happen but in case new errors // are added in the future. } } }}
Elements can be configured to allow for multiple answers through their App Spec using three values:
Maximum votes per user: This specifies how many votes a user can cast, either on the same option or on multiple options. E.g. a user can emit 5 votes for a given question, either all 5 on the same option, or spread through multiple options.
Maximum and Minimum options per vote: This specifies the minimum and maximum options a user must include in their vote. E.g. a user must pick at least 2 options and at most 3.
In some scenarios, you may wish to validate that a given answer is correct before attempting to submit it. For instance, this could be helpful if you want to highlight in red that the user's choice is not a valid response and accompany with some explanatory text on how to correct it.
To that effect, we offer you a method called validateAnswer() that lets you perform the same validations the answer() method performs, and reports any potential errors in the same manner.
// You can validate your answer at any point, so as to provide// feedback to your user about what went wrong:try {validateAnswer(element, index);} catch (e) {// The same error handling as was done when calling `answer`}
// You can validate your answer at any point, so as to provide// feedback to your user about what went wrong:do {try element.validateAnswer(index)}catch {// The same error handling as was done when calling `answer`}
try { element.validateAnswer(index)} catch (e: ElementVoteError) {// The same error handling as was done when calling `answer`}
Displaying the results of an Interactive Element
After the user selects their response to the Element, you may want to show them what other people are saying. The platform collects responses and periodically sends aggregated stats back to all connected clients. Here's how you receive those results:
functiondisplayPoll(element) {// ...const { results } = element;if (results ===null) {// We don't have yet results, so reflect the case on the UIreturn; }// We are able to show results to the userconstvoteCount=results.map((result) =>result.votes);constvotePercentage=results.map((result) =>result.percentage);}
funcdisplayPoll(_element: Element) {// ...let results = element.resultsiflet results = results {// We are able to show results to the userlet voteCount = results.map { $0.voteCount }let votePercentage = results.map { $0.votePercentage } } else {// We don't have yet results, so reflect the case on the UI }}
You can also display to the user which of all the options is the correct option to select, which is a critical feature when building for instance a Quiz.
The following snippet showcases how we check if the user has already submitted an answer, and if so, we obtain the correct option. Notice that depending on how you configure your Element in the App Spec, the correct option may be revealed at different times, so it's possible that the user has answered, but the real answer is not yet received. This is common when building Prediction Elements.
if (element.userAnswer ===null) {return;}constcorrectOptionIndex=element.correctOption;// Highlight the correct option from your collection of options