Home > Software engineering >  How to write a Future method in foreach concisely
How to write a Future method in foreach concisely

Time:11-19

I'm a beginner in Scala. Is there a concise way to write the following nested case statement?

def delete(
  client : TwitterRestClient,
  userId : Long,
  keyword : String) : Unit = {
client.userTimelineForUserId(userId).onComplete{
  case Success(value) => {
    value.data.filter(_.text.contains(keyword)).foreach(x => {
      client.deleteTweet(x.id).onComplete{
        case Success(value) => println(s"Success: $value")
        case Failure(exception) => println(s"Fail: $exception")
      }
    })
  }
  case Failure(exception) => println(s"Fail:$exception")
}

CodePudding user response:

Slightly different way using flatMap, sequencing Futures and using collect instead of filter and map:

def delete(
  client : TwitterRestClient,
  userId : Long,
  keyword : String) : Unit = {

  client
      .userTimelineForUserId(userId)
      .flatMap(ratedData => Future.sequence(ratedData.data.collect {
        case tweet if tweet.text.contains(keyword) => client.deleteTweet(tweet.id)
      }))
      .onComplete {
        case Success(value) => println(s"Success: $value")
        case Failure(exception) => println(s"Fail: $exception")
      }
}

I have only compiled the code, dint run it.

  • Related