hurshi / dio-http-cache

http cache lib for Flutter dio like RxCache
Apache License 2.0
274 stars 223 forks source link

how can i set cache mechanism for Retrofit #55

Closed pishguy closed 3 years ago

pishguy commented 4 years ago
abstract class MyApis{
  factory MyApis(Dio dio, {String baseUrl}) = _MyApis;

  @GET("/login")
  Future<HttpResponse<PageInformation>> login(@DioOptions() Options options);

  static MyApis create() {
    final dio = Dio();
    dio.options.headers['Content-Type'] = 'application/json';
    dio.options.receiveTimeout = 60000;
    dio.options.connectTimeout = 120000;
    return _MyApis(dio);
  }
}
hurshi commented 4 years ago

I'm sorry, it's not supported yet. maybe later.

danilof commented 3 years ago

@hurshi Thank you for the great library!

@MahdiPishguy It is working on retrofit also:

Try this:

abstract class MyApis{
  factory MyApis(Dio dio, {String baseUrl}) = _MyApis;

  @GET("/login")
  Future<HttpResponse<PageInformation>> login({@DioOptions() Options options}); //change to named paremeter to make it optional

  static MyApis create() {
    final dio = Dio();
    dio.options.headers['Content-Type'] = 'application/json';
    dio.options.receiveTimeout = 60000;
    dio.options.connectTimeout = 120000;
    //add cache interceptor to DIO
dio.interceptors.add(
        DioCacheManager(CacheConfig(baseUrl: apiUrl))
            .interceptor);

    return _MyApis(dio);
  }
}

And then you can add cache option to your api call like so:

//create options 
Options cacheOptions = buildCacheOptions(Duration(days: 7), forceRefresh: true);
//and then use it in api call      
... login(options: cacheOptions);

And you have working solution for Retrofit!

pishguy commented 3 years ago

@danilof thanks so much