美文网首页Android开发
Kotlin 简化多回调函数

Kotlin 简化多回调函数

作者: 猪爸爸Hulk | 来源:发表于2019-01-10 15:17 被阅读3次
    Kotlin 简化多回调函数

    这里只是简单的例子,并没有实际意义,可以通过这个方法改造Android的TextWatcher ViewPager以及网络回调等各种多回调

        "123".setXListener(object :XListener{
            override fun onStart(name: String, time: String) {
    
            }
    
            override fun onProgress(progress: Int) {
    
            }
    
            override fun onEnd(path: String, time: Int) {
    
            }
    
        })
    
        "123".setXlistenerHelpter {
            OnStart { name, time ->
    
            }
    
            OnProgress {progress ->
    
            }
    
            OnEnd { path, time ->
    
            }
        }
    

    源码

    interface XListener {
        fun onStart(name: String, time: String)
        fun onProgress(progress: Int)
        fun onEnd(path: String, time: Int)
    }
    
    class XListenerHelper : XListener {
    
        private var tmpStart: ((String, String) -> Unit)? = null
        private var tmpProgress: ((Int) -> Unit)? = null
        private var tmpEnd: ((String, Int) -> Unit)? = null
    
        override fun onStart(name: String, time: String) {
            tmpStart?.invoke(name, time)
        }
    
        fun OnStart(start: (name: String, time: String) -> Unit) {
            tmpStart = start
        }
    
        override fun onProgress(progress: Int) {
            tmpProgress?.invoke(progress)
        }
    
        fun OnProgress(progress: (progress: Int) -> Unit) {
            tmpProgress = progress
        }
    
        override fun onEnd(path: String, time: Int) {
            tmpEnd?.invoke(path, time)
        }
    
        fun OnEnd(end: (path: String, time: Int) -> Unit) {
            tmpEnd = end
        }
    
    }
    
    fun String.setXListener(listener: XListener) {
    
    }
    
    fun String.setXlistenerHelpter(listener: (XListenerHelper.() -> Unit)) {
        setXListener(XListenerHelper().apply { listener })
    }
    

    相关文章

      网友评论

        本文标题:Kotlin 简化多回调函数

        本文链接:https://www.haomeiwen.com/subject/codarqtx.html