Skip to content

Commit bce55b4

Browse files
authored
Only loop and check isAlive in MongoCursor.next() when cursor is tailable (#725)
1 parent 2e4d8f6 commit bce55b4

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

Sources/MongoSwift/AsyncAwait/MongoCursor+AsyncSequence.swift

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,17 +50,25 @@ extension MongoCursor: AsyncSequence, AsyncIteratorProtocol {
5050
* - `DecodingError` if an error occurs decoding the server's response to a `T`.
5151
*/
5252
public func next() async throws -> T? {
53-
while try await self.isAlive() {
54-
if Task.isCancelled {
55-
return nil
56-
}
57-
if let doc = try await self.tryNext() {
58-
return doc
59-
}
60-
await Task.yield()
53+
guard !Task.isCancelled else {
54+
return nil
6155
}
6256

63-
return nil
57+
switch self.cursorType {
58+
case .nonTailable:
59+
return try await self.next().get()
60+
case .tailable, .tailableAwait:
61+
while try await self.isAlive() {
62+
if Task.isCancelled {
63+
return nil
64+
}
65+
if let doc = try await self.tryNext() {
66+
return doc
67+
}
68+
await Task.yield()
69+
}
70+
return nil
71+
}
6472
}
6573

6674
/**

Sources/MongoSwift/MongoCursor.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ public class MongoCursor<T: Codable>: CursorProtocol {
3838

3939
private let wrappedCursor: Cursor<MongocCursor>
4040

41+
internal let cursorType: MongoCursorType
42+
4143
/// The `EventLoop` this `MongoCursor` is bound to.
4244
internal let eventLoop: EventLoop?
4345

@@ -67,6 +69,7 @@ public class MongoCursor<T: Codable>: CursorProtocol {
6769
self.client = client
6870
self.decoder = decoder
6971
self.eventLoop = eventLoop
72+
self.cursorType = cursorType ?? .nonTailable
7073

7174
self.wrappedCursor = try Cursor(
7275
mongocCursor: MongocCursor(referencing: cursorPtr),

0 commit comments

Comments
 (0)