com.spotify.mobius.extras.connections.MergeConnectablesConnection Maven / Gradle / Ivy
/*
* -\-\-
* Mobius
* --
* Copyright (c) 2017-2020 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.
* -/-/-
*/
package com.spotify.mobius.extras.connections;
import static com.spotify.mobius.internal_util.Preconditions.checkArgument;
import static com.spotify.mobius.internal_util.Preconditions.checkIterableNoNulls;
import static com.spotify.mobius.internal_util.Preconditions.checkNotNull;
import com.spotify.mobius.Connectable;
import com.spotify.mobius.Connection;
import com.spotify.mobius.functions.Consumer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class MergeConnectablesConnection implements Connection {
private final CopyOnWriteArrayList> connections;
public static Connection create(
List> connectables, Consumer output) {
return new MergeConnectablesConnection<>(connectables, output);
}
public static Connection create(
Connectable fst, Connectable snd, Consumer output) {
return create(Arrays.asList(fst, snd), output);
}
private MergeConnectablesConnection(List> connectables, Consumer output) {
checkIterableNoNulls(connectables);
checkArgument(connectables.size() > 0);
final Consumer consumer = checkNotNull(output);
List> cs = new ArrayList<>(connectables.size());
for (Connectable connectable : connectables) {
cs.add(connectable.connect(consumer));
}
connections = new CopyOnWriteArrayList<>(cs);
}
@Override
public void accept(A value) {
synchronized (connections) {
if (connections.size() == 0) {
throw new IllegalStateException("Calling accept on an already disposed connection");
}
}
for (Connection c : connections) {
c.accept(value);
}
}
@Override
public void dispose() {
List> cs = new ArrayList<>(connections);
synchronized (connections) {
connections.clear();
}
for (Connection c : cs) {
c.dispose();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy