Combine assign(to🔛) crashes every time

Hi,

I wanted to start using Combine and I wrote a class to load an API token and assign it to self once loaded.

Here is the class:

class API {
    
    private var token: String?
    
    func loadToken() {
        tokenPublisher()
            .replaceEmpty(with: nil)
            .replaceError(with: nil)
            .eraseToAnyPublisher() // Not needed really
            .receive(on: DispatchQueue.main)
            .assign(to: \.token, on: self)
            .cancel()
    }
    
    private func tokenPublisher() -> AnyPublisher<String?, Never> {
        return Just<String?>("someToken").eraseToAnyPublisher()
    }
}

let api = API()
api.loadToken()

When I use this code in my app, I get an EXC_BREAKPOINT error at .assign(to: \.token, on: self).
When I use it in Xcode Playground, I get an EXC_BAD_INSTRUCTION error there.
When I use it in Playgrounds App on Mac, I get an There was an error running your playground... at the same location.

My code seems to compile fine, so I was wondering if this is Combine or my code. Removing the .eraseToAnyPublisher() does not make a difference. Uncommenting assign does.

Thanks in advance.

It seems that .replaceEmpty(with: nil) and .replaceError(with: nil) are the issues. Maybe because the publisher has a failure type of Never?

Moreover .receive(on: DispatchQueue.main) prevents the value from being assigned. At least didSet is not called.

In my case, swapping of .replaceEmpty(with: nil) and .replaceError(with: nil) fixed the crash, but still curious what causes the issue.

Terms of Service

Privacy Policy

Cookie Policy