Created
September 13, 2019 18:27
-
-
Save stargazing-dino/078456d1e701b6fec73c6bbd5fe55a8a to your computer and use it in GitHub Desktop.
Continuous Requests Mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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