Skip to content

Commit 60859c4

Browse files
pixlwavestefanceriu
authored andcommitted
Add a basic example of using a timeline.
1 parent 106bc4a commit 60859c4

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

docs/Getting Started.md

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,52 @@ let handle = try await roomListService.allRooms().entries(listener: listener)
8282
await syncService.start()
8383
```
8484

85-
Finally we can send messages into a room (with built in support for markdown).
85+
When we're ready to display the events from a room we use the timeline API.
86+
87+
```swift
88+
class TimelineItemListener: TimelineListener {
89+
/// The loaded items for this room's timeline
90+
var timelineItems: [TimelineItem] = []
91+
92+
func onUpdate(diff: [TimelineDiff]) {
93+
// Update the timeline items on each update.
94+
for update in diff {
95+
switch update.change() {
96+
case .reset:
97+
timelineItems = update.reset()!
98+
default:
99+
break // Handle all the other cases accordingly.
100+
}
101+
}
102+
}
103+
}
104+
105+
// Fetch the room from the listener and initialise it's timeline.
106+
let room = listener.rooms.first!
107+
if !room.isTimelineInitialized() {
108+
try await room.initTimeline(eventTypeFilter: nil, internalIdPrefix: nil)
109+
}
110+
let timeline = try await room.fullRoom().timeline()
111+
112+
// Listen to timeline item updates.
113+
let timelineItemsListener = TimelineItemListener()
114+
let timelineHandle = await timeline.addListener(listener: timelineItemsListener)
115+
116+
// Wait for the items array to be updated…
117+
118+
// Get the event contents from an item.
119+
let timelineItem = timelineItemsListener.timelineItems.last!
120+
if let messageEvent = timelineItem.asEvent()?.content().asMessage() {
121+
print(messageEvent)
122+
}
123+
```
124+
125+
Finally we can send messages into the room (with built in support for markdown).
86126

87127
```swift
88128
// Create the message content from a markdown string.
89129
let message = messageEventContentFromMarkdown(md: "Hello, World!")
90130

91-
// Send the message content to the first room in the list.
92-
_ = try await listener.rooms.first?.fullRoom().timeline().send(msg: message)
131+
// Send the message content via the room's timeline (so that we show a local echo).
132+
_ = try await timeline.send(msg: message)
93133
```
94-

0 commit comments

Comments
 (0)