.net 4.5 async syntax - .net-4.5

I wrote the code below,
Task.Factory.StartNew<int>(async () =>
{
await Task.Delay(1000);
return 42;
});
but the read line appeared under the "async" keyword, and the code cannot compiled due to some syntax error, can anybody advise me what to do?
Thx a lot!

You probably want to use Task.Run, which has more natural syntax for async lambdas:
var task = Task.Run(async () =>
{
await Task.Delay(1000);
return 42;
});

You have to return a Task<T>, like so:
Task.Factory.StartNew<Task<int>>(async () =>
{
await Task.Delay(1000);
return 42;
});
The async keyword requires to return Task, Task<T> or void. Read more about it: async (C# Reference).

Related

Dart: How to test a function that takes a function as a parameter?

i been trying to unit test a function that takes a function as a parameter the unit test returns null value on the function that im testing so may i ask how to unit test this kind of function in dart.
this is the function that i want to test
final result = await _appStateNotifier.guard(
() => _authService.requestTempPassword(username: credentials.username),
);
and this is how i test it but got an error type 'Null' is not a subtype of type 'Future<Result<ErrorObject, String>>'
when(() => mockAuthService.requestTempPassword(username: tCredentials.username))
.thenAnswer((_) async => successMessage);
when(() => mockStateNotifier.guard(
() => mockAuthService.requestTempPassword(username: tCredentials.username),
),
).thenAnswer((_) async => const Success(successMessage));
await notifier.onRequestTempPassword(credentials: tCredentials);
and this is the guard clause function
Future<Result<ErrorObject, T>> guard<T>(Future<T> Function() function) async {
try {
final data = await future();
return Success(data);
} on FailureException catch (e) {
return Error(e);
} catch (e, s) {
return Error(e);
}
}
thank you
Your Future<Result<ErrorObject, T>> excludes the possibility of having a Null result. If you want to allow Null, then you need to make it nullable, see https://dart.dev/null-safety/understanding-null-safety
I'm not fluent with Flutter, so the syntax might be off, but as far as I understand, you could change that to
Future<Result<ErrorObject, T>>?
in order to make it nullable. Let me know if I'm totally off with the syntax.
EDIT
It turns out that the solution finally applied was putting the when method in the setpup function before the test run, as #Ken Verganio described in the comment section.

Not able to print debug message while unit testing in Flutter

I am testing a pretty straightforward use-case in Flutter. Inside the use-case class, I have a function that I'm invoking from my test. And I want to add some debug print statements to print the value of some variables inside the function of use-case. But it's not getting printed anywhere. How can I achieve this?
The function in Use-case.
Future<Either<Failure, List<Contest>>> call(NoParams params) async {
final result = await repository.getAllContests();
final currentDateTime = DateTime.now();
List<Contest> ongoingContests = [];
result.fold(
(l) => throw ServerException(),
(allContestList) => () {
for (var contest in allContestList) {
var contestStartTime = DateTime.parse(contest.start_time);
var contestEndTime = DateTime.parse(contest.end_time);
print(contestEndTime); //print statement
}
});
return Right(ongoingContests);
}
}
The test function
test('Should return only the ongoing contests', () async {
when(mockHomepageRepository.getAllContests()).thenAnswer((_) async =>
const Right([tContest, tOngoingContest, tUpcomingContest]));
final result = await getOngoingContests(NoParams()); //invoking the function
expect(result, const Right([tOngoingContest]));
verify(mockHomepageRepository.getAllContests());
verifyNoMoreInteractions(MockHomepageRepository());
});

Sockets and Future Functions in Dart

Summarize the Problem.
I am trying to write an async function that returns data when a receive is completed from a socket. I am having trouble returning the correct data from my async function. The error I am receiving is that the rtn variable is not set and can be null.
Describe what you've tried.
I've tried writing the async function but haven't been getting the desired result. I tried using the late keyword for the variable rtn but that resulted in a runtime exception that the variable was null.
Show some code.
Below, is the function giving me problems. Any advice or resources would be welcomed. I tried going over the Flutter documentation for async but it wasn't too helpful for me.
What I want is that the network data is returned from this async function.
Future<int> fetchNumVideos() async {
int rtn;
Socket.connect(baseStationAddresses[0],
baseStationPort, timeout: const Duration(seconds: 5)).then((socket) =>
{
socket.listen((data) {
String socketData = String.fromCharCodes(data);
print("socketData: $socketData");
rtn = int.parse(socketData);
},
onDone: ((){
socket.destroy();
})
),
}).catchError((onError) {
rtn = 0;
});
return rtn;
}
Thank you!
This issue has been solved by pskink's comment.
The solution was to use the Completer class.
Future<int> fetchNumVideos() async {
final completer = Completer<int>();
Socket.connect(baseStationAddresses[0],
baseStationPort, timeout: const Duration(seconds: 5)).then((socket) =>
{
socket.listen((data) {
String socketData = String.fromCharCodes(data);
print("socketData: $socketData");
completer.complete(int.parse(socketData));
},
onDone: ((){
socket.destroy();
})
),
}).catchError((onError) {
completer.complete(0);
});
return completer.future;
}

Is there a difference whether using await with return in Dart?

In my flutter project, say there's a foo(int x) async function. And bar() async that looks like:
Future bar() async {
return foo(3);
}
The bar() function is just a simple capsule for foo(int x) with a certain parameter. And bar() is used as the future in a FutureBuilder.
I'm not sure if I should use await with return. I can't find related documentations online. So what's the difference between return foo(3) and return await foo(3)? Thank you!
No difference whatsoever.
Technically, using await first might wait for the Future to resolve before returning from the function, but you won't be able to tell the difference.
A Future is returned either way.
The async there is useless too, it might as well just be an arrow:
Future bar() => foo(3);
If it were not the last statement, and a return statement, this could matter, as pointed out in the comments, take the following:
Future bar() async {
try {
return await foo(3);
} catch(error) {
return baz;
}
}
If foo rejects, then it matters quite a lot, as it would be handled by the callee, not the caller.
Since you are returning Future, in this exact case, even if you don`t await it, the foo(3) will return Future instead and it is the exact thing your function wants to return. and if u await it there, then it will await in the function and then return the value.
you don`t even need await in this case if foo return Future. Then the caller of bar will instead await the bar.
Using this simple example you can see in which order prints yield:
Future<void> fetchUserOrder() {
return Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}
void main() async {
await fetchUserOrder();
print('Fetching user order...');
}
fetchUserOrder() returns Future. So if we call it in main with await, it will receive the Future, execute it and await for the result. Only then proceed to the second print of the main.
We could've written the fetchUserOrder() in such a fashion:
Future<void> fetchUserOrder() async {
return await Future.delayed(const Duration(seconds: 2), () => print('Large Latte'));
}
And it wouldn't have had changed the result. It would work the same, the only difference is shorter code and that now you understand how it works.
Use https://dartpad.dev/ to launch these examples.

Chaing async method on Dart

I have following class.
class Element {
Future<Element> findById(var id)async {
await networkRequest();
return this;
}
Futute<Element> click() async {
await networkRequest();
return this;
}
}
I want to achieve the something like.
main() async {
var element = Element();
await element.findyById("something").click();
}
But I'm not able to do so because element.findById() returns future. How can I chain these async methods.
While there's no special syntax to chain futures, there are two semantically equivalent ways to do what you want:
1) Two separate await calls:
await element.findById("something");
await click();
2) Chaining with then:
await element.findById("something").then(() => click());
Use this,
await (await Element().findById("1")).click();
final el = await element.findyById("something");
await el.click();