Equivalent of iOS NSNotificationCenter in Android?

前端 未结 5 760
无人共我
无人共我 2021-01-31 05:51

Is there an equivalent of the iOS class NSNotificationCenter in Android ? Are there any libraries or useful code available to me ?

5条回答
  •  灰色年华
    2021-01-31 06:06

    If you don't want to use Observer - it can be problematic in cases you want a Fragment to be your Observer cause you can't extend more then one class- You can use google's Guava Library (https://code.google.com/p/guava-libraries/) for "Function" and "Multimap" - although you can use as well HashMap> for the subscibersCollection

    and implement something like this:

        import java.util.Collection;
    import com.google.common.collect.ArrayListMultimap;
    import com.google.common.base.Function;
    
    public class EventService {
    
        ArrayListMultimap> subscibersCollection;
    
        private static EventService instance = null;
    
        private static final Object locker = new Object();
    
        private EventService() {
            subscibersCollection = ArrayListMultimap.create();
        }
    
        public static EventService getInstance() {
            if (instance == null) {
                synchronized (locker) {
                    if (instance == null) {
                        instance = new EventService();
                    }
                }
            }
            return instance;
        }
    
        /**
         * Subscribe to the notification, and provide the callback functions in case
         * notification is raised.
         * 
         * @param notification
         *            - notification name
         * @param func
         *            - function to apply when notification is raised
         */
        public void addSubscription(String notification, Function func) {
            synchronized (subscibersCollection) {
                if (!subscibersCollection.containsEntry(notification, func)) {
                    subscibersCollection.put(notification, func);
                }
            }
        }
    
        /**
         * Remove subscription from notification
         */
        public void removeSubscription(String notification,
                Function func) {
            synchronized (subscibersCollection) {
                subscibersCollection.remove(notification, func);
            }
        }
    
        /**
         * raise notification for all its subscribers
         * 
         * @param notification
         *            - notification name
         * @param data
         *            - update data
         */
        public void publish(String notification, Object data) {
            Collection> observableList = subscibersCollection
                    .get(notification);
            for (Function func : observableList) {
                func.apply(data);
            }
        }
    }
    

提交回复
热议问题