如何在Kotlin DSL中设置Rx Action使用者

时间:2019-03-28 15:13:55

标签: kotlin dsl rx-kotlin2

我正在研究Kotlin命令的RxKotlin DSL的开发

我有一些工作要做,但是我会改进设置Rx ActionConsumer(s)的方法。

我当前拥有的代码类似于:-

@SequenceDsl
class ExperimentalBuilder {

    companion object {
        private val emptyAction = Action { }
        private val emptyConsumer: Consumer<in Throwable> = Consumer { }
    }


    var uuid: String = ""
    var onError: Consumer<in Throwable> = emptyConsumer
    var onComplete: Action = emptyAction
    var doFinally: Action = emptyAction
    var doLoginRefreshFail: Action = emptyAction

    fun build(): Experimental = Experimental(uuid, onError, onComplete, doFinally, doLoginRefreshFail)

}

import io.reactivex.Single
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

data class Experimental(
    val uuid: String,
    val onError: Consumer<in Throwable>,
    val onComplete: Action,
    val doFinally: Action,
    val doLoginRefreshFail: Action
) : Morpheme() {

    override fun execute() {

        Single.just("")
            .subscribeOn(Schedulers.single())
            .ignoreElement()
            .doOnSubscribe {disposable -> COMPOSITE_DISPOSABLE.add(disposable) }
            .doOnComplete(onComplete)
            .doOnError(onError)
            .doFinally(doFinally)
            .doAfterTerminate(doAfterTerminate())
            .subscribe()
    }
}

,我使用以下代码:-

  val experimental = Dsl().experimental {
            uuid = "09876"

            onComplete = Action {
                Log.d("EXPERIMENT", "ON COMPLETE")
                Log.d("EXPERIMENT", "ON COMPLETE")
            }

            onError = Consumer {
                    throwable -> Log.e("EXPERIMENT", "ON ERROR", throwable)
            }

            doFinally =  Action {
                Log.d("EXPERIMENT", "DO FINALLY")
            }

            doLoginRefreshFail =  Action {
                Log.d("EXPERIMENT", "DO LOGIN REFRESH FAIL")
            }
        }

        experimental.execute()

        Log.d("DSL", "what $experimental")

设置ActionConsumer时,我想“改进”的代码是这样的

  onComplete = Action {
    Log.d("EXPERIMENT", "ON COMPLETE")
    Log.d("EXPERIMENT", "ON COMPLETE")
  }

  onError = Consumer {
    throwable -> Log.e("EXPERIMENT", "ON ERROR", throwable)
  }

这是我可以用来设置“ onCompile”操作的唯一方法吗?

例如我是否必须提到“动作{}”,还是可以使用“速记”版本来达到相同的结果?

1 个答案:

答案 0 :(得分:1)

您可以在DSL中定义这样的功能

fun onComplete(onCompleteCallback: ()->Unit) {
  onComplete = Action(onCompleteCallback)
}

可以这样使用:

onComplete {
    Log.d("EXPERIMENT", "ON COMPLETE")
    Log.d("EXPERIMENT", "ON COMPLETE")
}

我希望不会有太多需要它的人

通常kotlin可以帮助进行SAM转换,但这似乎只适用于函数调用,而不能直接设置时使用 并且一旦定义了一个功能,您可能还要确保包装正确完成 也可以考虑进行这些功能inline