|
@@ -1,8 +1,9 @@
|
|
|
package com.livelike.flickersearchlibrary.service.logic
|
|
|
|
|
|
-import android.util.Log
|
|
|
import com.livelike.flickersearchlibrary.api.FlickrApi
|
|
|
import com.livelike.flickersearchlibrary.api.model.Photo
|
|
|
+import com.livelike.flickersearchlibrary.api.model.response.ApiResponse
|
|
|
+import com.livelike.flickersearchlibrary.api.utils.executeApiCall
|
|
|
import com.livelike.flickersearchlibrary.service.FlickrService
|
|
|
|
|
|
/**
|
|
@@ -12,53 +13,26 @@ internal class FlickrServiceLogic(private val api: FlickrApi) : FlickrService {
|
|
|
|
|
|
private val cachedPhotos = mutableListOf<Photo>()
|
|
|
|
|
|
- private val LOG_TAG = "FlickrService"
|
|
|
-
|
|
|
override suspend fun search(searchQuery: String?) =
|
|
|
searchQuery?.let {
|
|
|
- updateCachedPhotos(searchQuery)
|
|
|
+ val response = executeApiCall {
|
|
|
+ api.search(searchQuery)
|
|
|
+ }
|
|
|
+ if (response is ApiResponse.Success) {
|
|
|
+ cachedPhotos.clear()
|
|
|
+ cachedPhotos.addAll(response.body)
|
|
|
+ }
|
|
|
+
|
|
|
cachedPhotos
|
|
|
} ?: emptyList()
|
|
|
|
|
|
override suspend fun getRecentPhotos(): List<Photo> {
|
|
|
- return runCatching {
|
|
|
- val response = api.getRecent()
|
|
|
- if (response.isSuccessful) {
|
|
|
- response.body()?.photosPage?.photos ?: emptyList()
|
|
|
- } else {
|
|
|
- throw Exception(
|
|
|
- "Flickr API responded with error: ${
|
|
|
- response.errorBody().toString()
|
|
|
- }"
|
|
|
- )
|
|
|
- }
|
|
|
- }.onFailure { exception: Throwable ->
|
|
|
- Log.d(
|
|
|
- LOG_TAG,
|
|
|
- "Exception occurred when executing API call: ${exception.message}"
|
|
|
- )
|
|
|
- }.getOrDefault(emptyList())
|
|
|
- }
|
|
|
-
|
|
|
- private suspend fun updateCachedPhotos(searchQuery: String) =
|
|
|
- runCatching {
|
|
|
- val response = api.search(searchQuery)
|
|
|
- if (response.isSuccessful) {
|
|
|
- response.body()?.let {
|
|
|
- cachedPhotos.clear()
|
|
|
- cachedPhotos.addAll(it.photosPage.photos)
|
|
|
- }
|
|
|
- } else {
|
|
|
- throw Exception(
|
|
|
- "Flickr API responded with error: ${
|
|
|
- response.errorBody().toString()
|
|
|
- }"
|
|
|
- )
|
|
|
- }
|
|
|
- }.onFailure { exception: Throwable ->
|
|
|
- Log.d(
|
|
|
- LOG_TAG,
|
|
|
- "Exception occurred when executing API call: ${exception.message}"
|
|
|
- )
|
|
|
+ val response = executeApiCall {
|
|
|
+ api.getRecent()
|
|
|
}
|
|
|
+ return when (response) {
|
|
|
+ is ApiResponse.Success -> response.body
|
|
|
+ is ApiResponse.Error -> emptyList()
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|