class DslRequest {
private lateinit var mUrl: String
private lateinit var mMethod: String
private lateinit var mSuccess: (DslResponse) -> Unit
private lateinit var mFailed: (DslResponse) -> Unit
companion object {
private val TAG = "DslRequest"
internal fun build(init: DslRequest.() -> Unit): DslRequest {
val wrap = DslRequest()
init.invoke(wrap)
wrap.execute()
return wrap
}
internal fun execute(request: DslRequest) {
request.execute()
}
}
fun url(text: () -> String) {
mUrl = text.invoke()
}
fun method(text: ()-> String) {
mMethod = text.invoke()
}
fun success(block: (DslResponse) -> Unit) {
mSuccess = block
}
fun failed(block: (DslResponse) -> Unit) {
mFailed = block
}
fun execute() {
Log.d(TAG, "execute: ${this}")
}
override fun toString(): String {
return "url: ${mUrl} method: ${mMethod} "
}
}
使用
val request = DslRequest.build {
url { "baidu.com" }
method { "get" }
success { }
failed { }
}
DslRequest.execute(request)
更多用法参考:https://juejin.im/entry/5a9b2320f265da238f12014d