1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.mojo.bindings; 6 7 import org.chromium.mojo.system.MojoException; 8 9 import java.util.Collections; 10 import java.util.Set; 11 import java.util.WeakHashMap; 12 13 /** 14 * A {@link ConnectionErrorHandler} that delegate the errors to a list of registered handlers. This 15 * class will use weak pointers to prevent keeping references to any handlers it delegates to. 16 */ 17 public class DelegatingConnectionErrorHandler implements ConnectionErrorHandler { 18 19 /** 20 * The registered handlers. This uses a {@link WeakHashMap} so that it doesn't prevent the 21 * handler from being garbage collected. 22 */ 23 private final Set<ConnectionErrorHandler> mHandlers = 24 Collections.newSetFromMap(new WeakHashMap<ConnectionErrorHandler, Boolean>()); 25 26 /** 27 * @see ConnectionErrorHandler#onConnectionError(MojoException) 28 */ 29 @Override onConnectionError(MojoException e)30 public void onConnectionError(MojoException e) { 31 for (ConnectionErrorHandler handler : mHandlers) { 32 handler.onConnectionError(e); 33 } 34 } 35 36 /** 37 * Add a handler that will be notified of any error this object receives. 38 */ addConnectionErrorHandler(ConnectionErrorHandler handler)39 public void addConnectionErrorHandler(ConnectionErrorHandler handler) { 40 mHandlers.add(handler); 41 } 42 43 /** 44 * Remove a previously registered handler. 45 */ removeConnectionErrorHandler(ConnectionErrorHandler handler)46 public void removeConnectionErrorHandler(ConnectionErrorHandler handler) { 47 mHandlers.remove(handler); 48 } 49 } 50