Reputation: 2697
I Have function like below:
Future getArticles() async {
try {
_loadingArticleController.sink.add(true);
Response response;
var dio = ApiProvider.dio();
response = await dio.get("/article/get-random-lang?category=1&lang=${translations.currentLanguage}");
var data = response.data['data'];
print(data);
articleList.clear();
if (response.statusCode == 200) {
for (int i = 0; i < data.length; i++) {
model = articleFromJson(json.encode(data[i]));
articleList.add(model);
}
// sink to the stream
_articlesController.sink.add(articleList);
_loadingArticleController.sink.add(false);
await Storage.storeArticles(data);
}
else
{
throw new DioError(
response: Response(
statusCode: response.data['status'],
data: {
'message': response.data['message']
}
)
);
}
}
on DioError catch (e) {
var articles = await Storage.getArticles();
if (articles.length > 0) {
articleList.clear();
for (int i = 0; i < articles.length; i++) {
Article model = await compute(articleFromJson, json.encode(articles[i]));
articleList.add(model);
}
_articlesController.sink.add(articleList);
} else {
_articlesController.sink.add([]);
}
_loadingArticleController.sink.add(false);
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
if (e.response != null) {
print(e.response);
print(e.response.headers);
print(e.response.request);
} else {
// Something happen
print(e);
}
}
}
In above function i have an anticipation, if function become error then take data from storage. However, I dont know how to using try catch if timeout occurs, let's says for 10 seconds.
any idea?
Thank You In Advance
Upvotes: 0
Views: 299
Reputation: 2714
I have an idea, you could create a timer which is going to be 10 seconds and put the function inside your try block. Now if the 10 seconds are done and you want your function to be interrupted, you can cancel it by just return noting in the function and call cancelTimer
to break it.
Timer _timer;
_startTimer() {
_cancelTimer();
_timer = Timer.periodic(Duration(seconds: 10), (timer) {
_cancelTimer();
});
}
_cancelTimer() {
_timer?.cancel();
}
Upvotes: 1