gpt4 book ai didi

java - 在java/kotlin中通过inject()将变量传递给类构造函数

转载 作者:行者123 更新时间:2023-12-02 01:59:55 24 4
gpt4 key购买 nike

我的主类(class)设置如下:

class MyView : View() {    

val controller: PollController by inject()
etc
}

我想传递一个变量(例如路径文件的字符串)

class PollController : Controller() {

val currentData = SimpleStringProperty()
val stopped = SimpleBooleanProperty(true)

val scheduledService = object : ScheduledService<DataResult>() {
init {
period = Duration.seconds(1.0)
}
override fun createTask() : Task<DataResult> = FetchDataTask()
}

fun start() {
scheduledService.restart()
stopped.value = false
}

inner class FetchDataTask : Task<DataResult>() {

override fun call() : DataResult {
return DataResult(SimpleStringProperty(File(**path**).readText()))
}

override fun succeeded() {
this@PollController.currentData.value = value.data.value // Here is the value of the test file
}

}

}

[DataResult 只是一个 SimpleStringProperty 数据类]

以便 PollController 类中的函数可以引用路径文件。我不明白注入(inject)是如何工作的; @Inject 始终保持红色,添加构造函数会抛出 Controller() 对象返回

最佳答案

这是作用域的一个很好的用例。作用域隔离了 Controller 和 View 模型,以便您可以为不同版本的资源拥有不同的作用域。如果您还添加一个 ViewModel 来保存您的上下文,您可以执行以下操作:

class MyView : View() {
val pc1: PollController by inject(Scope(PollContext("somePath")))
val pc2: PollController by inject(Scope(PollContext("someOtherPath")))
}

现在将上下文对象添加到您的 Controller 中,以便您可以从 Controller 实例中的任何函数访问它。

class PollController : Controller() {
val context : PollContext by inject()
}

上下文对象可以包含输入/输出变量。在此示例中,它将输入路径作为参数。请注意,这样的 ViewModel 无法由框架实例化,因此您必须像我上面所示的那样手动将其中一个放入 Scope 中。

class PollContext(path: String) : ViewModel() {
val pathProperty = SimpleStringProperty(path)
var path by pathProperty

val currentDataProperty = SimpleStringProperty()
var currentData by currentDataProperty
}

关于java - 在java/kotlin中通过inject()将变量传递给类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51757883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com