ios – optional execution path with combine


The issue here is related to the error types. When using Just(userId), it returns a publisher with a completion of Never. However, your function is declared to return a Publisher with an error of type Error. To fix this, you need to introduce an error using the setFailureType operator on Just(userId).

func save(_ user: User, roles: [Role]?) -> AnyPublisher<Int?, Error> {
    return repository.save(user)
        .flatMap { [weak self] userId -> AnyPublisher<Int?, Error> in
            if let roles = roles {
                return repository.updateByUserId(userId, roles: roles)
                    .map { _ in userId }
                    .eraseToAnyPublisher()
            } else {
                return Just(userId)
                    .setFailureType(to: Error.self) // Introduce an error type
                    .eraseToAnyPublisher()
            }
        }
        .eraseToAnyPublisher()
}

By using setFailureType(to: Error.self), you are effectively making Just(userId) conform to the expected error type, allowing it to fit into the AnyPublisher<Int?, Error> type.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img