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

  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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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!