Swift Combine: CurrentValueSubject, the most useful subject of all times

KD Knowledge Diet
2 min readAug 24, 2022

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

  1. Access value directly with currentValueSubject.value.
  2. Subscribe to Subject.
  3. Passing down new value with Subject.
  4. Sending completion finished with Subject.

Let’s look at one by one!

CurrentValueSubject

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.

Access Directly

You can directly access value with currentUserId.value without subscribing. This itself is super useful.

[2] Subscribe to Subject

Subscribe to Subject

You can also subscribe to Subject like any other combine publishers.

[3] Passing down new values with Subject

Passing Down

This is the characteristic of Subject. Publisher that you can continuously send new values down!

[4] Sending completion finished with Subject.

Sending completion .finished

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

  1. Access value directly with currentValueSubject.value.
  2. Subscribe to Subject.
  3. Passing down new value with Subject.
  4. Sending completion finished with Subject.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!