Skip to content

Commit 350c843

Browse files
committed
add waitForConnection
1 parent 14a6c7c commit 350c843

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/Conversation.swift

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,36 +61,45 @@ public final class Conversation: Sendable {
6161
self.init(client: RealtimeAPI(connectingTo: request))
6262
}
6363

64-
@MainActor public func whenConnected<E>(_ callback: @Sendable () async throws(E) -> Void) async throws(E) {
64+
/// Wait for the connection to be established
65+
@MainActor public func waitForConnection() async {
6566
while true {
6667
if connected {
67-
return try await callback()
68+
return
6869
}
6970

7071
try? await Task.sleep(for: .milliseconds(500))
7172
}
7273
}
7374

75+
/// Execute a block of code when the connection is established
76+
@MainActor public func whenConnected<E>(_ callback: @Sendable () async throws(E) -> Void) async throws(E) {
77+
await waitForConnection()
78+
try await callback()
79+
}
80+
7481
/// Make changes to the current session
75-
/// Note that this will fail if the session hasn't started yet.
82+
/// Note that this will fail if the session hasn't started yet. Use `whenConnected` to ensure the session is ready.
7683
public func updateSession(withChanges callback: (inout Session) -> Void) async throws {
7784
guard var session = await session else {
7885
throw ConversationError.sessionNotFound
7986
}
8087

8188
callback(&session)
8289

83-
try await updateSession(session)
90+
try await setSession(session)
8491
}
8592

86-
public func updateSession(_ session: Session) async throws {
93+
/// Set the configuration of the current session
94+
public func setSession(_ session: Session) async throws {
8795
// update endpoint errors if we include the session id
8896
var session = session
8997
session.id = nil
9098

9199
try await client.send(event: .updateSession(session))
92100
}
93101

102+
/// Send a client event to the server
94103
public func send(event: ClientEvent) async throws {
95104
try await client.send(event: event)
96105
}

0 commit comments

Comments
 (0)