Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replaceEmpty/replaceNil/replaceError with publisher parameter #46

Closed
yhkaplan opened this issue Jul 28, 2020 · 1 comment
Closed

replaceEmpty/replaceNil/replaceError with publisher parameter #46

yhkaplan opened this issue Jul 28, 2020 · 1 comment

Comments

@yhkaplan
Copy link

I was looking at for something like RxSwift's ifEmpty(switchTo:), and there appeared to be a solution in
rxswift-to-combine-cheatsheet, but current versions of Combine do not offer replaceEmpty(with publisher: Publisher). I'm thinking something like the below would work, but what do you think? If it's okay, I'll go ahead and make a pull request.

public extension Publisher where Output: Collection {
    func replaceEmpty(with publisher: AnyPublisher<Output, Failure>) -> AnyPublisher<Output, Failure> {
        flatMap { (output: Output) -> AnyPublisher<Output, Failure> in
            if output.isEmpty { return publisher }
            return Just(output)
                .setFailureType(to: Failure.self)
                .eraseToAnyPublisher()
        }
        .eraseToAnyPublisher()
    }
}
@freak4pc
Copy link
Member

freak4pc commented Aug 8, 2020

Hey @yhkaplan, I think you've misunderstood how ifEmpty(switchTo:) works.

It isn't meant to work on empty/non-empty collections, but on empty Observables.

That means, a.ifEmpty(switchTo: b) will switch into the second observable if a completed without emitting anything, see DefaultIfEmpty in ReactiveX: http://reactivex.io/documentation/operators/defaultifempty.html

It should be easy enough to make this operator, but your implementation is of something else :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants