gpt4 book ai didi

java - Kotlin,响应式(Reactive)编程 : How to consume the value of one function output to another one

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

我对 Project reactor 库和使用 Kotlin 进行响应式(Reactive)编程非常陌生,并尝试实现 flatmap 等功能, flatMapIterable , subscribe等等
现在的问题是我正在尝试使用 flatMapIterable 将一个函数的 o/p 用于另一个函数,并且在使用后我试图通过将第一个函数的输出和第二个函数的输出传递给新类的另一个函数来订阅它。
现在当我尝试使用函数 1 的 o/p 时,我看不到值,我只看到 Mono<>Flux<> .

下面是更多解释的代码片段

var result = employerService.getEmployee("Active") // return value is Mono<GetEmployeeStatusListResult>
result.flatMapIterable(GetEmployeeStatusListResult::emps)
.flatMap {
employerService.getUsersById(it.userId) // it is of type GetEmployeeStatusListResult.emps and value returned from employerService.getUsersById(it.userId) is of type GetUserResult class created
}.subscribe {
aService.createContact(result, it)
}

现在在第 4 行,我期待 userIdit.userId ,但是当我在第 6 行检查结果时,我没有得到预期的值列表,它只是为我提供了 MonomapFuesable ,带有映射器和源。

谁能帮我理解我应该做什么,因为我的整个议程是将计算值从第 1 行和第 4 行传递到第 6 行函数。
请提出更多问题,如果我没有提供所需的信息,我对此很陌生。
提前致谢 !!

[更新]:我已经通过以下方式解决了这个问题:
```
employerService.getEmployee("Active") // return value is Mono<GetEmployeeStatusListResult>
.flatMapIterable(GetEmployeeStatusListResult::emps)
.flatMap {
employerService.getUsersById(it.userId).map{x->Pair(it,x)} // it is of type GetEmployeeStatusListResult.emps and value returned from employerService.getUsersById(it.userId) is of type GetUserResult class created
}.subscribe {
aService.createContact(it.first, it.second)
}

```

最佳答案

从上面提供的信息中很难确定,但我认为它看起来像是对 employerService.getUsersById 的调用。没有返回 Publisher .从您的评论中,我猜它正在返回一个实际值,GetUserResult ,而不是 Mono .我相信,下面是一组模拟的类,它们显示了预期的结果。也许将以下内容与您所拥有的进行比较,看看您是否能发现不同之处?

data class Employee(val userId: String)
data class GetEmployeeStatusListResult(val emps: List<Employee>)
data class GetUserResult(val employee: Employee)

class EmployerService {
fun getEmployee(status: String) = Mono.just(GetEmployeeStatusListResult(listOf(Employee("a"))))
fun getUsersById(userId: String) = Mono.just(GetUserResult(Employee("a")))
}

fun test() {
val employerService = EmployerService()
employerService
.getEmployee("Active")
.flatMapIterable(GetEmployeeStatusListResult::emps)
.flatMap {
employerService.getUsersById(it.userId)
}.subscribe {
// Here "it" is a GetUserResult object
}
}

如果,在 subscribe ,您需要从调用 getEmployee 中检索到的初始值。以及调用 getUsersById 的结果那么您可以将这两个值包装在 Pair 中如下所示:
employerService
.getEmployee("Active")
.flatMapIterable(GetEmployeeStatusListResult::emps)
.flatMap { emp ->
employerService.getUsersById(emp.userId).map { emp to it }
}.subscribe {
// Here "it" is a Pair<Employee, GetUserResult>
}

关于java - Kotlin,响应式(Reactive)编程 : How to consume the value of one function output to another one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002509/

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