Skip to content

Commit

Permalink
examples of tasks and futures
Browse files Browse the repository at this point in the history
  • Loading branch information
SandroMaglione committed Dec 16, 2022
1 parent ebe22ad commit 2bcda29
Show file tree
Hide file tree
Showing 3 changed files with 154 additions and 34 deletions.
66 changes: 32 additions & 34 deletions example/read_write_file/main.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:io';

import 'package:fpdart/fpdart.dart';

/**
Expand Down Expand Up @@ -35,48 +36,45 @@ void main() async {
///
/// Since we are using [TaskEither], until we call the `run` method,
/// no actual reading is performed.
final task = readFileAsync('./assets/source_ita.txt').flatMap(
(linesIta) => readFileAsync('./assets/source_eng.txt').map(
(linesEng) => linesIta.zip(linesEng),
),
);

/// Run the reading process
final result = await task.run();

/// Check for possible error in the reading process
result.fold(
/// Print error in the reading process
final task = readFileAsync('./assets/source_ita.txt')
.flatMap(
(linesIta) => readFileAsync('./assets/source_eng.txt').map(
(linesEng) => linesIta.zip(linesEng),
),
)
.map(
(iterable) => iterable.flatMapWithIndex(
(tuple, index) => searchWords.foldLeftWithIndex<List<FoundWord>>(
[],
(acc, word, wordIndex) =>
tuple.second.toLowerCase().split(' ').contains(word)
? [
...acc,
FoundWord(
index,
word,
wordIndex,
tuple.second.replaceAll(word, '<\$>'),
tuple.first,
),
]
: acc,
),
),
)
.match(
(l) => print(l),
(r) {
/// If no error occurs, search the words inside each sentence
/// and compute list of sentence in which you found a word.
final list = r.flatMapWithIndex((tuple, index) {
return searchWords.foldLeftWithIndex<List<FoundWord>>(
[],
(acc, word, wordIndex) =>
tuple.second.toLowerCase().split(' ').contains(word)
? [
...acc,
FoundWord(
index,
word,
wordIndex,
tuple.second.replaceAll(word, '<\$>'),
tuple.first,
),
]
: acc,
);
});

(list) {
/// Print all the found [FoundWord]
list.forEach(
(e) => print(
'${e.index}, ${e.word}(${e.wordIndex}): ${e.english}_${e.italian}\n'),
);
},
);

/// Run the reading process
await task.run();
}

/// Read file content in `source` directory using [TaskEither]
Expand Down
92 changes: 92 additions & 0 deletions example/src/task/task_and_future.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import 'package:fpdart/fpdart.dart';

/// Helper functions ⚙️ (sync)
String addNamePrefix(String name) => "Mr. $name";
String addEmailPrefix(String email) => "mailto:$email";
String decodeName(int code) => "$code";

/// API functions 🔌 (async)
Future<String> getUsername() => Future.value("Sandro");
Future<int> getEncodedName() => Future.value(10);

Future<String> getEmail() => Future.value("@");

Future<bool> sendInformation(String usernameOrName, String email) =>
Future.value(true);

Future<bool> withFuture() async {
late String usernameOrName;
late String email;

try {
usernameOrName = await getUsername();
} catch (e) {
try {
usernameOrName = decodeName(await getEncodedName());
} catch (e) {
throw Exception("Missing both username and name");
}
}

try {
email = await getEmail();
} catch (e) {
throw Exception("Missing email");
}

try {
final usernameOrNamePrefix = addNamePrefix(usernameOrName);
final emailPrefix = addEmailPrefix(email);
return await sendInformation(usernameOrNamePrefix, emailPrefix);
} catch (e) {
throw Exception("Error when sending information");
}
}

TaskEither<String, bool> withTask() => TaskEither.tryCatch(
getUsername,
(_, __) => "Missing username",
)
.alt(
() => TaskEither.tryCatch(
getEncodedName,
(_, __) => "Missing name",
).map(
decodeName,
),
)
.map(
addNamePrefix,
)
.flatMap(
(usernameOrNamePrefix) => TaskEither.tryCatch(
getEmail,
(_, __) => "Missing email",
)
.map(
addEmailPrefix,
)
.flatMap(
(emailPrefix) => TaskEither.tryCatch(
() => sendInformation(usernameOrNamePrefix, emailPrefix),
(_, __) => "Error when sending information",
),
),
);

Task<int> getTask() => Task(() async {
print("I am running [Task]...");
return 10;
});

Future<int> getFuture() async {
print("I am running [Future]...");
return 10;
}

void main() {
Task<int> taskInt = getTask();
Future<int> futureInt = getFuture();

// Future<int> taskRun = taskInt.run();
}
30 changes: 30 additions & 0 deletions example/src/task_option/future_task_option.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import 'package:fpdart/fpdart.dart';

late Future<Map<String, Object>?> example;

final taskOp = TaskOption.flatten(
(TaskOption.fromTask(
Task<Map<String, Object>?>(
() => example,
).map(
(ex) => Option.fromNullable(ex).toTaskOption(),
),
)),
);

/// New API `toOption`: from `Map<String, Object>?` to `Option<Map<String, Object>>`
final taskOpNew = TaskOption<Map<String, Object>>(
() async => (await example).toOption(),
);

/// Using `Option.fromNullable`, the [Future] cannot fail
final taskOpNoFail = TaskOption<Map<String, Object>>(
() async => Option.fromNullable(await example),
);

/// Using `Option.fromNullable` when the [Future] can fail
final taskOpFail = TaskOption<Map<String, Object>?>.tryCatch(
() => example,
).flatMap<Map<String, Object>>(
(r) => Option.fromNullable(r).toTaskOption(),
);

0 comments on commit 2bcda29

Please sign in to comment.