Skip to content

Instantly share code, notes, and snippets.

@stargazing-dino
Created September 13, 2019 18:27
Show Gist options
  • Save stargazing-dino/078456d1e701b6fec73c6bbd5fe55a8a to your computer and use it in GitHub Desktop.
Save stargazing-dino/078456d1e701b6fec73c6bbd5fe55a8a to your computer and use it in GitHub Desktop.
Continuous Requests Mixin
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:mobile/utils/lifecycle_event_handler.dart';
/// Attaches to a [Widget] and calls [fetchData] every [interval] seconds
/// or upon app reactivation.
mixin ContinuousRequest<T extends StatefulWidget> on State<T> {
/// A subscription that calls [fetch] data every [interval] seconds
StreamSubscription _streamSubscription;
/// A handler to the app lifecycle
LifecycleEventHandler _handler;
/// The interval in `seconds` between calls to [fetchData]
int interval = 30;
/// Only true on initial load
bool isLoading = true;
@override
void initState() {
// Wrapped in future to avoid any issues with calling setState inside fetchData
Future(() async {
await fetchData();
setState(() => isLoading = false);
});
_streamSubscription = Stream.periodic(
Duration(seconds: interval),
).listen((_) => fetchData());
_handler = LifecycleEventHandler(resumeCallBack: fetchData);
WidgetsBinding.instance.addObserver(_handler);
super.initState();
}
@override
void dispose() {
_streamSubscription?.cancel();
WidgetsBinding.instance.removeObserver(_handler);
super.dispose();
}
Future<void> fetchData() async {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment