-
Notifications
You must be signed in to change notification settings - Fork 156
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
Adds ConcatMap operator #68
Open
ohitsdaniel
wants to merge
7
commits into
CombineCommunity:main
Choose a base branch
from
ohitsdaniel:ConcatMap
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c618f4d
Adds ConcatMap operator
ohitsdaniel 20423b2
Changes completion test to check for upstream completion
ohitsdaniel d46de43
Adds Publishers.ConcatMap
ohitsdaniel 15176bc
fixup! Adds Publishers.ConcatMap
ohitsdaniel eb4cd7f
Publishes values of subsequent publisher after emptying publisher queue
ohitsdaniel 844178e
Adds Inner and OuterSink for ConcatMap
ohitsdaniel 80ba6dd
Weakifies outerSink in innerSink
ohitsdaniel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,237 @@ | ||
// | ||
// ConcatMap.swift | ||
// CombineExt | ||
// | ||
// Created by Daniel Peter on 22/11/2020. | ||
// Copyright © 2020 Combine Community. All rights reserved. | ||
// | ||
|
||
#if canImport(Combine) | ||
import Combine | ||
|
||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) | ||
public extension Publisher { | ||
/// Transforms an output value into a new publisher, and flattens the stream of events from these multiple upstream publishers to appear as if they were coming from a single stream of events. | ||
/// | ||
/// Mapping to a new publisher will keep the subscription to the previous one alive until it completes and only then subscribe to the new one. This also means that all values sent by the new publisher are not forwarded as long as the previous one hasn't completed. | ||
/// | ||
/// - parameter transform: A transform to apply to each emitted value, from which you can return a new Publisher | ||
/// | ||
/// - returns: A publisher emitting the values of all emitted publishers in order. | ||
func concatMap<T, P>( | ||
_ transform: @escaping (Self.Output) -> P | ||
) -> Publishers.ConcatMap<P, Self> where T == P.Output, P: Publisher, Self.Failure == P.Failure { | ||
return Publishers.ConcatMap(upstream: self, transform: transform) | ||
ohitsdaniel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) | ||
public extension Publishers { | ||
struct ConcatMap<NewPublisher, Upstream>: Publisher where NewPublisher: Publisher, Upstream: Publisher, NewPublisher.Failure == Upstream.Failure { | ||
public typealias Transform = (Upstream.Output) -> NewPublisher | ||
public typealias Output = NewPublisher.Output | ||
public typealias Failure = Upstream.Failure | ||
|
||
public let upstream: Upstream | ||
public let transform: Transform | ||
|
||
public init( | ||
upstream: Upstream, | ||
transform: @escaping Transform | ||
) { | ||
self.upstream = upstream | ||
self.transform = transform | ||
} | ||
|
||
public func receive<S: Subscriber>(subscriber: S) | ||
where Output == S.Input, Failure == S.Failure { | ||
subscriber.receive( | ||
subscription: Subscription( | ||
upstream: upstream, | ||
downstream: subscriber, | ||
transform: transform | ||
) | ||
) | ||
} | ||
} | ||
} | ||
|
||
// MARK: - Subscription | ||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) | ||
private extension Publishers.ConcatMap { | ||
final class Subscription<Downstream: Subscriber>: Combine.Subscription where | ||
Downstream.Input == NewPublisher.Output, | ||
Downstream.Failure == Failure | ||
{ | ||
private var sink: OuterSink<Downstream>? | ||
|
||
init( | ||
upstream: Upstream, | ||
downstream: Downstream, | ||
transform: @escaping Transform | ||
) { | ||
self.sink = OuterSink( | ||
upstream: upstream, | ||
downstream: downstream, | ||
transform: transform | ||
) | ||
} | ||
|
||
func request(_ demand: Subscribers.Demand) { | ||
sink?.demand(demand) | ||
} | ||
|
||
func cancel() { | ||
sink = nil | ||
} | ||
} | ||
} | ||
|
||
// MARK: - Sink | ||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) | ||
private extension Publishers.ConcatMap { | ||
final class OuterSink<Downstream: Subscriber>: Subscriber where | ||
Downstream.Input == NewPublisher.Output, | ||
Downstream.Failure == Upstream.Failure | ||
{ | ||
private let lock = NSRecursiveLock() | ||
|
||
private let downstream: Downstream | ||
private let transform: Transform | ||
|
||
private var upstreamSubscription: Combine.Subscription? | ||
private var innerSink: InnerSink<Downstream>? | ||
|
||
private var bufferedDemand: Subscribers.Demand = .none | ||
|
||
init( | ||
upstream: Upstream, | ||
downstream: Downstream, | ||
transform: @escaping Transform | ||
) { | ||
self.downstream = downstream | ||
self.transform = transform | ||
|
||
upstream.subscribe(self) | ||
} | ||
|
||
func demand(_ demand: Subscribers.Demand) { | ||
lock.lock(); defer { lock.unlock() } | ||
if let innerSink = innerSink { | ||
innerSink.demand(demand) | ||
} else { | ||
bufferedDemand = demand | ||
} | ||
|
||
upstreamSubscription?.requestIfNeeded(.unlimited) | ||
} | ||
|
||
func receive(_ input: Upstream.Output) -> Subscribers.Demand { | ||
lock.lock(); defer { lock.unlock() } | ||
let transformedPublisher = transform(input) | ||
|
||
if let innerSink = innerSink { | ||
innerSink.enqueue(publisher: transformedPublisher) | ||
} else { | ||
innerSink = InnerSink( | ||
outerSink: self, | ||
upstream: transformedPublisher, | ||
downstream: downstream | ||
) | ||
|
||
innerSink?.demand(bufferedDemand) | ||
} | ||
|
||
return .unlimited | ||
} | ||
|
||
func receive(subscription: Combine.Subscription) { | ||
lock.lock(); defer { lock.unlock() } | ||
upstreamSubscription = subscription | ||
} | ||
|
||
func receive(completion: Subscribers.Completion<Upstream.Failure>) { | ||
lock.lock(); defer { lock.unlock() } | ||
innerSink = nil | ||
downstream.receive(completion: completion) | ||
cancelUpstream() | ||
} | ||
|
||
func cancelUpstream() { | ||
lock.lock(); defer { lock.unlock() } | ||
upstreamSubscription.kill() | ||
} | ||
|
||
deinit { cancelUpstream() } | ||
} | ||
|
||
final class InnerSink<Downstream: Subscriber>: CombineExt.Sink<NewPublisher, Downstream> where | ||
Downstream.Input == NewPublisher.Output, | ||
Downstream.Failure == Upstream.Failure | ||
{ | ||
private weak var outerSink: OuterSink<Downstream>? | ||
private let lock: NSRecursiveLock = NSRecursiveLock() | ||
|
||
private var hasActiveSubscription: Bool | ||
private var publisherQueue: [NewPublisher] | ||
|
||
init( | ||
outerSink: OuterSink<Downstream>, | ||
upstream: NewPublisher, | ||
downstream: Downstream | ||
) { | ||
self.outerSink = outerSink | ||
self.hasActiveSubscription = false | ||
self.publisherQueue = [] | ||
|
||
super.init( | ||
upstream: upstream, | ||
downstream: downstream | ||
) | ||
} | ||
|
||
func enqueue(publisher: NewPublisher) { | ||
lock.lock(); defer { lock.unlock() } | ||
if hasActiveSubscription { | ||
publisherQueue.append(publisher) | ||
} else { | ||
publisher.subscribe(self) | ||
} | ||
} | ||
|
||
override func receive(_ input: NewPublisher.Output) -> Subscribers.Demand { | ||
buffer.buffer(value: input) | ||
} | ||
|
||
override func receive(subscription: Combine.Subscription) { | ||
lock.lock(); defer { lock.unlock() } | ||
hasActiveSubscription = true | ||
|
||
super.receive(subscription: subscription) | ||
subscription.requestIfNeeded(buffer.remainingDemand) | ||
} | ||
|
||
override func receive(completion: Subscribers.Completion<Upstream.Failure>) { | ||
lock.lock(); defer { lock.unlock() } | ||
hasActiveSubscription = false | ||
|
||
switch completion { | ||
case .finished: | ||
if !publisherQueue.isEmpty { | ||
publisherQueue.removeFirst().subscribe(self) | ||
} | ||
case let .failure(error): | ||
buffer.complete(completion: .failure(error)) | ||
outerSink?.receive(completion: completion) | ||
} | ||
} | ||
} | ||
} | ||
|
||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) | ||
extension Publishers.ConcatMap.Subscription: CustomStringConvertible { | ||
var description: String { | ||
"ConcatMap.Subscription<\(Downstream.Input.self), \(Downstream.Failure.self)>" | ||
} | ||
} | ||
#endif |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure about this - why would it emit at all if it's only subscribed to after the completion of the previous one?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new, inner publisher could potentially emit before being subscribed to (Like a non-deferred future, i.e. hot observable)?
Example:
In this case, concatMap does not buffer 2 as the Publisher 1 hadn't completed when 2 was put onto the stream.
See
test_ignores_values_of_subsequent_while_previous_hasNot_completed
inCompactMapTests.swift
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In Rx, the concatMap assumes that inner Observables are cold and that the closure creates the Observable that is being subscribed to. I think it's correct to make that assumption here as well.