scalatwitter4jtwitter4s

How to write a Future method in foreach concisely


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")
}

Solution

  • 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.