Swift Combine: CurrentValueSubject, the most useful subject of all times
If you want to use the Swift Combine Framework well, you need to study the subjects provided by combine properly. Because it will be the backbone of your application using Combine! Today, I’m going to talk about CurrentValueSubject()
.
What is Subject in Combine?
Subject simply means Publisher that you can continuously send new values down! That’s why Combine Subject things come with method send()
. Don’t go deeper into the terms, it might confuse you.
Core Functionalities of CurrentValueSubject
- Access value directly with
currentValueSubject.value
. - Subscribe to Subject.
- Passing down new value with Subject.
- Sending completion finished with Subject.
Let’s look at one by one!
CurrentValueSubject
CurrentValueSubject has generic types. First Argument is for the datatype it holds and the second argument is for Error. You can give it Never
as a second argument, if you expect no errors at all or don’t intend to handle errors!
[1] Access value directly with currentValueSubject.value
.
You can directly access value with currentUserId.value
without subscribing. This itself is super useful.
[2] Subscribe to Subject
You can also subscribe to Subject like any other combine publishers.
[3] Passing down new values with Subject
This is the characteristic of Subject. Publisher that you can continuously send new values down!
[4] Sending completion finished with Subject.
After sending completion .finished
, nothing can pass!
What distinguishes CurrentValueSubject from Other Subjects?
Unlike PassthroughSubject
, CurrentValueSubject can hold a value. You can directly access it with currentValueSubject.value
.
Conclusion
- Access value directly with
currentValueSubject.value
. - Subscribe to Subject.
- Passing down new value with Subject.
- Sending completion finished with Subject.