Ecco il problema, ho una libreria che ha un metodo di blocco return Prova [T]. Ma poiché è un blocco, vorrei renderlo non-blocking usando Future [T]. Nel blocco futuro, vorrei anche calcolare qualcosa che dipende dal valore di ritorno del metodo di blocco dell'origine.Qual è il modo migliore per avvolgere il blocco Prova [T] in Future [T] in Scala?
Ma se io uso qualcosa di simile al di sotto, poi il mio nonBlocking
tornerà Futuro [Prova [T]] che è meno convincere dal Futuro [T] potrebbe rappresentare mancata [U] già, avrei preferito preferisco propagare l'eccezione a Future [T] è autonomo.
def blockMethod(x: Int): Try[Int] = Try {
// Some long operation to get an Int from network or IO
throw new Exception("Network Exception") }
}
def nonBlocking(x: Int): Future[Try[Int]] = future {
blockMethod(x).map(_ * 2)
}
Ecco quello che ho provato, mi basta usare .get
metodo future {}
blocco, ma non sono sicuro se questo è il modo migliore per farlo.
def blockMethod(x: Int): Try[Int] = Try {
// Some long operation to get an Int from network or IO
throw new Exception("Network Exception") }
}
def nonBlocking(x: Int): Future[Int] = future {
blockMethod(x).get * 2
}
È questo il modo corretto per farlo? O c'è un modo più idiomatico per convertire t Try [T] to Future [T]?
Se sai che stai bloccando, non si suppone per avvolgere il codice in 'blocking'? –
Potrebbe essere utile il metodo 'fromTry' per questo? http://www.scala-lang.org/api/current/#scala.concurrent.Future$ – stefanobaghino
Correzione automatica del mio commento precedente: 'fromTry' in realtà blocca, quindi non ci sono fortuna. – stefanobaghino