0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterAdvent Calendar 2024

Day 25

【Flutter】RiverpodのFutureProviderで直列、並列処理を行う

Posted at

前提

下記のように、リポジトリからデータを取得するRiverpodのFutureProviderを二つ作成します。

@Riverpod(keepAlive: false)
Future<User> userData(Ref ref) {
  final repo = ref.watch(localUserRepositoryProvider);
  return repo.getUserData();
}

@Riverpod(keepAlive: false)
Future<List<Notification>> notification(Ref ref) async {
  final repo = ref.watch(notificationRepositoryProvider);
  return repo.getNotification();
}

直列

@Riverpod()
Future<String> homePageData(Ref ref) async {
  try {
    // サンプルなので、取得した値は特に使ってません
    final notifications = await ref.watch(notificationProvider.future);
    final user = await ref.watch(userDataProvider.future);
    print(notifications);
    print(user);
  }  catch (e) {
    print(e);
  }

  // サンプルなので戻り値は適当にしてます
  return 'Hello world';
}

並列

@Riverpod()
Future<String> homePageData(Ref ref) async {
  try {
    // サンプルなので、取得した値は特に使ってません
    final (notifications, user) = await (
      ref.watch(notificationProvider.future),
      ref.watch(userDataProvider.future),
    ).wait;
    print(notifications);
    print(user);
  } on ParallelWaitError catch (e) {
    print(e.errors.$1);
    print(e.errors.$2);
    print(e.values.$1);
    print(e.values.$2);
  }

  // サンプルなので戻り値は適当にしてます
  return 'Hello world';
}

疑問

ParallelWaitErrorがキャッチできず、知っている方がいればコメントください。。。

  try {
    // サンプルなので、取得した値は特に使ってません
    final (notifications, user) = await (
      ref.watch(notificationProvider.future),
      ref.watch(userDataProvider.future),
    ).wait;
    print(notifications);
    print(user);
  } catch (e) {
    print(e.runtimeType);
  }

 上記のコードで、ParallelWaitError<(List<Notification>?, User?), (AsyncError?, AsyncError?)>が出力されるのですが、以下のようにしてもキャッチできませんでした。

  try {
    final (notifications, user) = await (
      ref.watch(notificationProvider.future),
      ref.watch(userDataProvider.future),
    ).wait;
    print(notifications);
    print(user);
  } on ParallelWaitError<(List<Notification>?, User?),
      (AsyncError?, AsyncError?)> catch (e) {
    // キャッチされない
    print(e.runtimeType);
  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?