RxDart fetch item for every item in stream and join results

Issue

I have a simple data class that represents a task:

class Task {
   String name;
   String userId;
}

And a stream of tasks:

class TaskDataSource {
   Stream<List<Task>> getAll() {
}

For every task I want to also fetch a user that is assigned to it:

class UsersDataSource {
   Stream<User> getById(String userId);
}

And finally combine a task with a user to create an object that contains user’s data as well as task’s data. I was playing with zip function as well as flatMap but couldn’t find a working solution. Any help would be appreciated.

Solution

Use Rx.forkJoinList:

class UserAndTasks {
  final User user;
  final Task task;

  UserAndTasks(this.user, this.task);
}  

void main() {
  UsersDataSource usersDataSource;
  TaskDataSource taskDataSource;

  taskDataSource
      .getAll()
      .flatMap(
        (tasks) => Rx.forkJoinList(tasks
            .map((task) => usersDataSource
                .getById(task.userId)
                .map((user) => UserAndTasks(user, task)))
            .toList()),
      )
      .listen((List<UserAndTasks> event) => print(event));
}

Answered By – Petrus Nguyễn Thái Học

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *