forked from spotify/Mobius.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompositeEventSourceBuilder.swift
56 lines (51 loc) · 2.32 KB
/
CompositeEventSourceBuilder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2019-2022 Spotify AB.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// A `CompositeEventSourceBuilder` gathers the provided event sources together and builds a single event source that
/// subscribes to all of them when its `subscribe` method is called.
public struct CompositeEventSourceBuilder<Event> {
private let eventSources: [AnyEventSource<Event>]
/// Initializes a `CompositeEventSourceBuilder`.
public init() {
self.init(eventSources: [])
}
private init(eventSources: [AnyEventSource<Event>]) {
self.eventSources = eventSources
}
/// Returns a new `CompositeEventSourceBuilder` with the specified event source added to it.
public func addEventSource<Source: EventSource>(_ source: Source)
-> CompositeEventSourceBuilder<Event> where Source.Event == Event {
let sources = eventSources + [AnyEventSource(source)]
return CompositeEventSourceBuilder(eventSources: sources)
}
/// Builds an event source that composes all the event sources that have been added to the builder.
///
/// - Returns: An event source which represents the composition of the builder’s input event sources. The type
/// of this source is an implementation detail; consumers should avoid spelling it out if possible.
public func build() -> AnyEventSource<Event> {
switch eventSources.count {
case 0:
return AnyEventSource { _ in AnonymousDisposable() }
case 1:
return eventSources[0]
default:
let eventSources = self.eventSources
return AnyEventSource { consumer in
let disposables = eventSources.map {
$0.subscribe(consumer: consumer)
}
return CompositeDisposable(disposables: disposables)
}
}
}
}