What is CurrentValueSubject in Swift Combine?

CurrentValueSubject is a type of Publisher in the Combine framework that allows you to emit a current value immediately upon subscription, and then continue to emit new values over time.

Unlike other types of Publishers that require an initial value to be passed in upon creation, CurrentValueSubject allows you to set an initial value when you create the Publisher, and then emit new values using the send(_:) method.

Here’s an example of how to create and use a CurrentValueSubject:

import Combine

// Create a CurrentValueSubject that emits integers
let subject = CurrentValueSubject<Int, Never>(0)

// Subscribe to the subject and print any new values that are emitted
subject.sink { value in
    print("New value: \(value)")
}

// Output: New value: 0

// Update the subject's value and see the subscriber receive the new value
subject.send(1)

// Output: New value: 1

In this example, we create a CurrentValueSubject that emits integers with an initial value of 0. We then subscribe to the subject using the sink method, which prints any new values that are emitted. We update the subject’s value using the send method, and see the subscriber receive the new value.

CurrentValueSubject is a useful type of Publisher for cases where you need to emit an initial value and then continue to emit new values over time, such as when you need to represent the current state of a user interface element or a shared data model.