Skip to content

Commit

Permalink
Dart 3.0 (#2)
Browse files Browse the repository at this point in the history
* flutter 3.10.0, deps

* either, dart 3.0

* cancel op

* cancel op

* better

* better
  • Loading branch information
hoc081098 authored Jun 15, 2023
1 parent de4d982 commit 3997ccd
Show file tree
Hide file tree
Showing 11 changed files with 392 additions and 195 deletions.
3 changes: 2 additions & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'package:batch_api_demo/main/bloc.dart';
import 'package:batch_api_demo/main/home_page.dart';
import 'package:batch_api_demo/main/main_bloc.dart';
import 'package:batch_api_demo/users_repo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc_pattern/flutter_bloc_pattern.dart';
Expand All @@ -25,6 +25,7 @@ class MyApp extends StatelessWidget {
useMaterial3: true,
colorSchemeSeed: Colors.purple,
),
debugShowCheckedModeBanner: false,
home: BlocProvider(
initBloc: (context) => MainBloc(usersRepo: context.get()),
child: const MyHomePage(),
Expand Down
76 changes: 0 additions & 76 deletions lib/main/bloc.dart

This file was deleted.

65 changes: 49 additions & 16 deletions lib/main/home_page.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'package:batch_api_demo/main/bloc.dart';
import 'package:batch_api_demo/main/state.dart';
import 'package:batch_api_demo/main/main_bloc.dart';
import 'package:batch_api_demo/main/main_state.dart';
import 'package:batch_api_demo/optional.dart';
import 'package:batch_api_demo/users_repo.dart';
import 'package:built_collection/built_collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc_pattern/flutter_bloc_pattern.dart';

Expand All @@ -23,14 +25,40 @@ class _MyHomePageState extends State<MyHomePage> {
return Scaffold(
appBar: AppBar(
title: const Text('Batch API demo'),
actions: [
IconButton(
onPressed: () => context.bloc<MainBloc>().fetch(),
icon: const Icon(Icons.refresh),
),
IconButton(
onPressed: () => context.bloc<MainBloc>().cancel(),
icon: const Icon(Icons.cancel),
),
RxStreamBuilder<bool>(
stream: UsersRepo.failed$,
builder: (context, state) => TextButton(
onPressed: UsersRepo.toggleFailed,
child: Text(
state ? 'failed' : 'succeed',
style: TextStyle(color: state ? Colors.red : Colors.green),
),
),
),
],
),
body: SizedBox.expand(
child: RxStreamBuilder<MainState>(
stream: context.bloc<MainBloc>().state$,
builder: (context, state) {
if (state.cancelled) {
return const Center(
child: Text('Cancelled'),
);
}

if (state.error.isNotEmpty) {
return Center(
child: Text('Error: ${state.error.valueOrNull()}'),
child: Text('Error: ${state.error.valueOrNull()!.message}'),
);
}

Expand All @@ -49,7 +77,7 @@ class _MyHomePageState extends State<MyHomePage> {
}

class UsersListView extends StatelessWidget {
final List<UserItem> items;
final BuiltList<UserItem> items;

const UsersListView({Key? key, required this.items}) : super(key: key);

Expand All @@ -59,7 +87,10 @@ class UsersListView extends StatelessWidget {
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return UserItemRow(item: item);
return UserItemRow(
key: ValueKey(item.user.id),
item: item,
);
},
);
}
Expand All @@ -74,17 +105,19 @@ class UserItemRow extends StatelessWidget {
Widget build(BuildContext context) {
return ListTile(
title: Text(item.user.name),
subtitle: item.isLoading
? Text(
'Loading...',
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Colors.red),
)
: item.user.avatarUrl != null
? Text('Avatar: ${item.user.avatarUrl}')
: const Text('No avatar'),
subtitle: switch ((item.isLoading, item.error)) {
(true, _) => Text(
'Loading...',
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Colors.red),
),
(_, Some(value: final error)) => Text('Error: ${error.message}'),
_ => item.user.avatarUrl != null
? Text('Avatar: ${item.user.avatarUrl}')
: const Text('No avatar'),
},
leading: const CircleAvatar(
child: Icon(Icons.person),
),
Expand Down
96 changes: 96 additions & 0 deletions lib/main/main_bloc.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import 'dart:async';

import 'package:batch_api_demo/main/main_state.dart';
import 'package:batch_api_demo/main/partial_state_change.dart';
import 'package:batch_api_demo/users_repo.dart';
import 'package:batch_api_demo/utils.dart';
import 'package:built_collection/built_collection.dart';
import 'package:disposebag/disposebag.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc_pattern/flutter_bloc_pattern.dart';
import 'package:rxdart_ext/rxdart_ext.dart';

const _batchSize = 4;
const _maxRetries = 3;

class MainBloc extends DisposeCallbackBaseBloc {
final Func0<void> fetch;
final Func0<void> cancel;

final StateStream<MainState> state$;

MainBloc._({
required Func0<void> dispose,
required this.fetch,
required this.cancel,
required this.state$,
}) : super(dispose);

factory MainBloc({
required UsersRepo usersRepo,
}) {
final fetchS = StreamController<void>();
final cancelS = PublishSubject<void>(sync: true);

final state$ = Rx.merge([
fetchS.stream.switchMap(
(_) => _fetchUsersAndAvatars(usersRepo)
.doOnCancel(
() => debugPrint('MainBloc._fetchUsersAndAvatars() cancelled!'))
.takeUntil(cancelS.stream),
),
cancelS.stream.asyncMap((event) => Future.value(UsersCancelledChange())),
])
.scan((state, change, _) => change.reduce(state), MainState.initial)
.publishState(MainState.initial);

return MainBloc._(
dispose: DisposeBag([
fetchS,
cancelS,
state$.connect(),
]).dispose,
fetch: fetchS.addNull,
cancel: cancelS.addNull,
state$: state$,
);
}
}

Stream<MainPartialStateChange> _fetchUsersAndAvatars(UsersRepo usersRepo) =>
usersRepo
.fetchUsers()
.exhaustMap(
(either) => either.fold(
ifLeft: (e) => Stream.value(UsersErrorChange(e)),
ifRight: (users) {
final items = users.map(UserItem.loading).toBuiltList();

return Rx.concat<MainPartialStateChange>([
Stream.value(UsersListChange(items)),
Stream.fromIterable(items)
.flatMapBatches(
(e) => _fetchAvatars(usersRepo, e.user), _batchSize)
.expand(identity),
]);
},
),
)
.startWith(UsersLoadingChange());

Stream<MainPartialStateChange> _fetchAvatars(
UsersRepo usersRepo,
User user,
) =>
retryEitherSingle<UserError, String>(
() => usersRepo.fetchUserAvatarUrl(user),
_maxRetries,
)
.map(
(either) => either.fold(
ifLeft: (e) => UserItem.failed(user, e),
ifRight: (avatarUrl) =>
UserItem.loaded(user.copyWithNewAvatarUrl(avatarUrl)),
),
)
.map(UserItemUpdatedChange.new);
Loading

0 comments on commit 3997ccd

Please sign in to comment.