Android equivalent to NSNotificationCenter

前端 未结 8 2075
旧时难觅i
旧时难觅i 2020-12-22 15:35

In the process of porting an iPhone application over to android, I am looking for the best way to communicate within the app. Intents seem to be the way to go, is this the b

8条回答
  •  太阳男子
    2020-12-22 16:26

    I wrote a wrapper that can do this same job, equivalent to iOS using LiveData

    Wrapper:

    class ObserverNotify {
        private val liveData = MutableLiveData()
    
    
        fun postNotification() {
            GlobalScope.launch {
                withContext(Dispatchers.Main) {
                    liveData.value = liveData.value
                }
            }
        }
    
        fun observeForever(observer: () -> Unit) {
            liveData.observeForever { observer() }
        }
    
        fun observe(owner: LifecycleOwner, observer: () -> Unit) {
            liveData.observe(owner) { observer()}
        }
    
    }
    
    class ObserverNotifyWithData {
        private val liveData = MutableLiveData()
    
    
        fun postNotification(data: T) {
            GlobalScope.launch {
                withContext(Dispatchers.Main) {
                    liveData.value = data
                }
            }
        }
    
        fun observeForever(observer: (T) -> Unit) {
            liveData.observeForever { observer(it) }
        }
    
        fun observe(owner: LifecycleOwner, observer: (T) -> Unit) {
            liveData.observe(owner) { observer(it) }
        }
    
    }
    

    Declaring observer types:

    object ObserverCenter {
        val moveMusicToBeTheNextOne: ObserverNotifyWithData by lazy { ObserverNotifyWithData() }
        val playNextMusic: ObserverNotify by lazy { ObserverNotify() }
        val newFCMTokenDidHandle: ObserverNotifyWithData by lazy { ObserverNotifyWithData() }
    }
    

    In the activity to observe:

    ObserverCenter.newFCMTokenDidHandle.observe(this) {
        // Do stuff
    }
    

    To notify:

    ObserverCenter.playNextMusic.postNotification()
    ObserverCenter.newFCMTokenDidHandle.postNotification("MyData")
    

提交回复
热议问题