Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
TruMan1 Avatar asked Sep 05 '25 02:09

TruMan1


1 Answers

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
}

like image 80
Raminder Singh Avatar answered Sep 07 '25 18:09

Raminder Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!