I’m testing out working with Combine and I’m experiencing some unexpected behaviour. Trying to observe a @Published var
from another class. I have two pieces of code.
Task {
await AuthManager.shared.$userID
.first()
.removeDuplicates()
.sink { user in
print(user)
}
.store(in: &cancellable)
}
In the above code the print statement will run two – three times. Why?
Task {
await AuthManager.shared.$userID
.dropFirst()
.removeDuplicates()
.sink { user in
print(user)
}
.store(in: &cancellable)
}
In the above code the print statement will run every time userID is changed as expected, accept on initialization. This makes sense to me.
My question is why does there seem to be multiple values for the first element in the stream?
The example code for dropFirst(_:)
seems to conflict with what I’m seeing. See below:
/// Omits the specified number of elements before republishing subsequent elements.
///
/// Use ``Publisher/dropFirst(_:)`` when you want to drop the first `n` elements from the upstream publisher, and republish the remaining elements.
///
/// The example below drops the first five elements from the stream:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cancellable = numbers.publisher
.dropFirst()
.sink { print("($0)", terminator: " ") }
// Prints: "2 3 4 5 6 7 8 9 10 "
///
/// - Parameter count: The number of elements to omit. The default is `1`.
/// - Returns: A publisher that doesn’t republish the first `count` elements.