我对Project reactor库和Kotlin的反应式编程非常陌生,并尝试实现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行,我从it.userId
中得到了预期的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>
}
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)
}
添加pair函数来获取这两个值并在订阅块中使用它!!谢谢大家!!