TruMan1
TruMan1

Reputation: 36098

How to convert a publisher to a CurrentValueSubject?

I have a publisher that my view's onReceive is subscribed to. Instead of duplicating logic in onAppear as well, I'd like the publisher in the onReceive to fire on first subscribe.

Is there a way to convert a publisher to a CurrentValueSubject? Here's what I'm trying to do:

var myPublisher: CurrentValueSubject<Void, Never> {
    Just(()) // Error: Cannot convert return expression of type 'Just<()>' to return type 'CurrentValueSubject<Void, Never>'
}

Is this possible or a better way to do this?

Upvotes: 4

Views: 4205

Answers (2)

Raminder Singh
Raminder Singh

Reputation: 61

You can assign a publisher to a CurrentValueSubject which you can then use in your code. Without duplicating the logic.

var oldPublisher: AnyPublisher <Void, Never>
    
private var cancellables = Set<AnyCancellable>()
    
var myCurrentValueSubject: CurrentValueSubject<Void, Never> {
    let subject = CurrentValueSubject<Void, Never>(())
    oldPublisher
      .assign(to: \.value, on: subject)
      .store(in: &cancellables)
    return subject
}

Upvotes: 6

donnywals
donnywals

Reputation: 7591

You can't convert publishers to CurrentValueSubject at will because it's a very specific type of publisher. Ask yourself whether you really need the type of myPublisher to be CurrentValueSubject<Void, Never> or if an AnyPublisher<Void, Never> would do.

var myPublisher: AnyPublisher <Void, Never> {
    Just(()).eraseToAnyPublisher()
}

Alternatively, if all you're trying to do is create an instance of CurrentValueSubject that has () as its initial value you could use this:

var myPublisher: CurrentValueSubject<Void, Never> {
    CurrentValueSubject<Void, Never>(())
}

Upvotes: 4

Related Questions