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

Add flatMapFirst #47

Open
mesheilah opened this issue Aug 12, 2020 · 5 comments
Open

Add flatMapFirst #47

mesheilah opened this issue Aug 12, 2020 · 5 comments

Comments

@mesheilah
Copy link

While there's no switchToFirst operator in Combine, I find it very challenging to implement flatMapFirst like operator from scratch, I'd suggest to start building this operator which's really useful for many use cases

@freak4pc
Copy link
Member

It's a great idea but would require and implementor with motivation that needs it. I don't have a use case for it so clearing my time to write it would be a bit tricky...

@troupmar
Copy link
Contributor

troupmar commented Aug 20, 2021

What about this?

public extension Publisher {
    func flatMapFirst<P: Publisher>(
        _ transform: @escaping (Output) -> P
    ) -> Publishers.FlatMap<Publishers.HandleEvents<P>, Publishers.Filter<Self>>
    where Self.Failure == P.Failure {
        var isRunning = false
        let lock = NSRecursiveLock()

        func set(isRunning newValue: Bool) {
            defer { lock.unlock() }
            lock.lock()

            isRunning = newValue
        }

        return self
            .filter { _ in !isRunning }
            .flatMap { output in
                transform(output)
                    .handleEvents(
                        receiveSubscription: { _ in
                            set(isRunning: true)
                        },
                        receiveCompletion: { _ in
                            set(isRunning: false)
                        },
                        receiveCancel: {
                            set(isRunning: false)
                        }
                    )
            }
    }
}

@danielt1263
Copy link
Contributor

@troupmar Care to add that as a pull request? I use flatMapFirst a lot in my RxSwift code so I would need this to switch to Combine. It would be nice to have everything I need in one library.

@troupmar
Copy link
Contributor

troupmar commented Feb 24, 2022

@danielt1263 Hi there, I will try to make a pull request but at this time I am very busy. The pull request will require some additional tests. At this point it would be useful if somebody could overview the implementation, at least to know if it seems to be correct. Then if I happen to have some time, I will be happy to complete it and prepare a pull request.

@troupmar
Copy link
Contributor

Here it is: #119

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

4 participants