Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to turn Future<Future<T>> into Future<T>?

I've got some code that submits a request to another thread which may or may not submit that request to yet another thread. That yields a return type of Future<Future<T>>. Is there some non-heinous way to immediately turn this into Future<T> that waits on the completion of the entire future chain?

I'm already using the Guava library to handle other fun concurrency stuff and as a replacement for Google Collections and its working well but I can't seem to find something for this case.

like image 537
Nik Avatar asked Jan 29 '10 21:01

Nik


People also ask

How do you make a Future in darts?

To create a Future object, we need to instantiate Future class by passing an invoker function (usually an anonymous function or fat arrow function) whose job is to return a value or another Future object that returns a value. A Future object has then and catchError methods which are used to register callback functions.

How do I get my Future void back?

When using Future<void> there is no need to explicitly return anything, since void is nothing, as the name implies. Also make sure you call deleteAll and writeAsString() using await .

How do you get the future object in Flutter?

get() method returns a Future object: Calling a function that returns a Future, will not block your code, that's why that function is called asynchronous. Instead, it will immediately return a Future object, which is at first uncompleted. Future<T> means that the result of the asynchronous operation will be of type T .

How do you find the future value?

You can calculate future value with compound interest using this formula: future value = present value x (1 + interest rate)n. To calculate future value with simple interest, use this formula: future value = present value x [1 + (interest rate x time)].


2 Answers

Another possible implementation that uses the guava libraries and is a lot simpler.

import java.util.concurrent.*;
import com.google.common.util.concurrent.*;
import com.google.common.base.*;

public class FFutures {
  public <T> Future<T> flatten(Future<Future<T>> future) {
    return Futures.chain(Futures.makeListenable(future), new Function<Future<T>, ListenableFuture<T>>() {
      public ListenableFuture<T> apply(Future<T> f) {
        return Futures.makeListenable(f);
      }
    });
  }
}
like image 150
Geoff Reedy Avatar answered Oct 09 '22 07:10

Geoff Reedy


Guava 13.0 adds Futures.dereference to do this. It requires a ListenableFuture<ListenableFuture>, rather than a plain Future<Future>. (Operating on a plain Future would require a makeListenable call, each of which requires a dedicated thread for the lifetime of the task (as is made clearer by the method's new name, JdkFutureAdapters.listenInPoolThread).)

like image 45
Chris Povirk Avatar answered Oct 09 '22 05:10

Chris Povirk