如何在 Kotlin DSL 中设置 Rx Action Consumer

How to set Rx Action Consumer in Kotlin DSL

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

我有一些工作但是我会改进我设置 Rx Action(s) 和 Consumer(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

时,我想要 "improve" 的代码是这样的
  onComplete = Action {
    Log.d("EXPERIMENT", "ON COMPLETE")
    Log.d("EXPERIMENT", "ON COMPLETE")
  }

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

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

例如我是否必须提及 "Action {}" 或是否有 "short-hand" 版本可用于实现相同的结果?

你可以在 DSL 中定义这样的函数

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

可以这样使用:

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

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

通常 kotlin 可以帮助进行 SAM 转换,但这似乎只适用于函数调用,而不是直接设置它 一旦你可以定义一个函数,你不妨确保包装正确完成 还可以考虑制作这些功能 inline