/// <summary> /// Add a new subscription for a certain service /// </summary> /// <param name="tag">The TypeTag for which to add the listener</param> /// <param name="listener">Listener to add (must be an instance of ServiceListener)</param> /// <returns>Returns a ServiceSubscription, which can be used to manage your subscription</returns> public ServiceSubscription AddServiceSubscription(TypeTag tag, ServiceListenerBase listener) { // Try to get the list of listeners, then add it. If it doesn't exist, create one first List<ServiceListenerBase> listenerList; // Try to get the list if it exists (and add the listener to it) if (serviceSubscriptions.TryGetValue(tag, out listenerList)) listenerList.Add(listener); else { // Otherwise create a new list and add it listenerList = new List<ServiceListenerBase> { listener }; serviceSubscriptions.Add(tag, listenerList); } // Now create an Action which can later be invoked by the user to cancel his subscription Action remover = () => { // Try to remove it from the list of listeners (categorized by TypeTag) // If it's the only element left in the list, just remove the entry as a whole List<ServiceListenerBase> listenerList_; if (serviceSubscriptions.TryGetValue(tag, out listenerList_)) if (listenerList.Count > 1) listenerList_.Remove(listener); else serviceSubscriptions.Remove(tag); }; // Now return an instance of ServiceSubscription so the user can manage his subscription return new ServiceSubscription(remover); }
/// <summary> /// Install a ServiceListener to listen for all services on the network of a particular TypeTag. /// </summary> /// <param name="serviceTag">TypeTag which identifies the service</param> /// <param name="listener">The ServiceListener to install for this particular TypeTag</param> /// <returns>Returns a ServiceSubscription, which can be used to manage this subscription to a service (and for example cancel it)</returns> public ServiceSubscription Whenever(TypeTag serviceTag, ServiceListenerBase listener) { System.Diagnostics.Debug.WriteLine("Installing service listener for TypeTag " + serviceTag.tag); return discoveryManager.serviceManager.subscriptionManager.AddServiceSubscription(serviceTag, listener); }