rxdata 0.3.0 rxdata: ^0.3.0 copied to clipboard
RxData allows to delegate fetching and caching behavior for your data.
RxData for Flutter #
RxData allows to delegate fetching and caching behavior for your data. Uses flutter_bloc
on the
background. Inspired by Revolut's RxData library.
Install #
flutter pub add rxdata
Usage #
First, define DataDelagete
object and specify Data
type.
final dataDelegate = DataDelegate<ApiResponse, Exception>(
fromNetwork: () async* {
// [fromNetwork] can yield multiple values before closing. You can sequentially fetch data and
// and yield them step by step.
final response = await getRequest();
yield response;
},
fromStorage: () async {
return loadFromSqlite();
},
toStorage: (value) async {
await saveToSqlite(value, 'my_key');
},
);
Then, use DataBuilder
to build your UI. DataBuilder
is only a wrapper around the BlocBuilder
.
You can also use DataListener
and DataConsumer
.
class ExampleWidget extends StatelessWidget {
const ExampleWidget({Key? key, required this.dataDelegate}) : super(key: key);
final DataDelegate<ApiResponse> dataDelegate;
@override
Widget build(BuildContext context) {
return Scaffold(
body: DataBuilder<ApiResponse>(
bloc: dataDelegate,
builder: (context, state) {
return Column(
children: [
if (state.isLoading) const CircularProgressIndicator(),
if (state.hasError) Text(state.error!.toString()),
if (state.hasValue) Text(state.value!.toString()),
],
);
},
),
);
}
}
Data
class has 3 fields:
value
: e.g.ApiResponse
or whatever data you need;error
: optional error, you might haveerror
andvalue
at the same time becausevalue
is not deleted when error is thrown;isLoading
: if you can expectvalue
orerror
to change soon.
You can then call dataDelegate.reload()
to fetch data again. Delegate will handle caching by
itself, provided that you specified your callbacks.
See example project for full usage.