Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: async abstract method

Tags:

dart

I'm trying to design an interface that abstracts long-running operation that should not be used from UI directly. To abstract it, I've created an abstract class with the only method to perform such an operation:

abstract class MakeSomething {

  Result make(Param param);

}

However I can't mark it as async (tried to place in before the signature, before the return type and before the semicolon). Is it possible, and, if yes - how?

like image 591
nyarian Avatar asked Apr 18 '19 15:04

nyarian


People also ask

How do you use async in Dart?

async: You can use the async keyword before a function's body to mark it as asynchronous. async function: An async function is a function labeled with the async keyword. await: You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function.

Is Dart synchronous or asynchronous?

Dart uses Future objects to represent asynchronous operations.

What's the difference between async and async * in Dart?

What is the difference between async and async* in Dart? The difference between both is that async* will always return a Stream and offer some syntax sugar to emit a value through the yield keyword. async gives you a Future and async* gives you a Stream.

Is abstract and can't be instantiated Dart?

An abstract class is a type of class that cannot be instantiated directly which means an object cannot be created from it. An abstract class cannot be instantiated but they can be sub-classed.


Video Answer


1 Answers

async functions almost always must return a Future. (An uncommon exception is async functions may have a void return type to be "fire-and-forget"; in such cases, there is no automatic way for the caller to be notified when the function completes.)

If you want your make function to be asynchronous and to provide a Result to the caller, it must return Future<Result>.

Note that async is not part of the function's type signature; async is a contextual keyword that enables the use of await inside the body of the function. That means that async is not very useful when declaring an abstract interface. The important part is that the function returns a Future, and derived classes can choose whether to implement that function using async/await.

like image 77
jamesdlin Avatar answered Sep 24 '22 04:09

jamesdlin