scala 将Future[Object]转换为另一个包含列表的Future[Object]

9wbgstp7  于 2023-10-18  发布在  Scala
关注(0)|答案(1)|浏览(132)

我有一个方法,它调用第三方端点来返回Future类型的Provider对象列表。现在我想调用这个方法,并将该对象转换为包含列表的不同的未来对象。以下是模型:

case class ThirdPartyProvidersResponse(providers: List[ThirdPartyProvider])

case class ThirdPartyProvider(
    id: String,
    config: List[Config]
)

// Convert ThirdPartyProvidersResponse to DomainProvidersResponse

case class DomainProvidersResponse(
    providers: List[DomainProviderResponse]
)

case class DomainProviderResponse(
    code: Option[DomainProviderType],
    enabled: Boolean
)

这是我试图实现的方法签名:

def getProviders(): Future[DomainProvidersResponse]

这是API方法的定义:

def getProvidersList(): Future[ThirdPartyProvidersResponse]

这就是我所尝试的:

def getProviders(): Future[DomainProvidersResponse] = {
  var providers: List[DomainProviderResponse] = List()
  thirdPartyServiceHttpClient.getProvidersList().map { response =>
    response.providers.map { providersList =>
      val provider = DomainProviderResponse(
        providerCode = DomainProviderType.findByName(providersList.id),
        enabled = true
      )
      providers :+= provider
    }
  }
  Future.successful(DomainProvidersResponse(providers = providers))
}

这段代码的问题在于同步。我需要等待future执行,然后才能返回结果。我们是否可以使用flatMap立即执行转换而无需显式同步来实现这一点?
任何帮助这是赞赏。我有Java背景,对Scala是个新手。

bvjveswy

bvjveswy1#

看起来你需要像map或for-comprehension这样的东西:

def getProviders(): Future[DomainProvidersResponse] =
  for {
    response <- thirdPartyServiceHttpClient.getProvidersList()
    domainProviders = response.providers.map { provider =>
     DomainProviderResponse(
        providerCode = DomainProviderType.findByName(providersList.id),
        enabled = true
      )
    }
  } yield DomainProvidersResponse(domainList)
// or
def getProviders(): Future[DomainProvidersResponse] =
  thirdPartyServiceHttpClient.getProvidersList().map { response =>
   response.providers.map { provider =>
     DomainProviderResponse(
        providerCode = DomainProviderType.findByName(providersList.id),
        enabled = true
      )
    }
  }.map { domainProviders =>
    DomainProvidersResponse(domainList)
  }

相关问题