我创建了一个用于学习的图库应用程序。图片是从不同的来源获取的,如 Pixabay、Unsplash、Imgur 等。我想将每个分页结果映射到我自己的名为 PhotoBO 的数据
我正在使用干净的架构,建议我更好的方法来处理
我想将所有寻呼响应映射PagingData<UnsplashPhoto>
到我的PagingData<PhotoBo >
class Resource<T> private constructor(val status: Status, val data: T?, val message: String?) {
enum class Status {
SUCCESS, ERROR, LOADING
}
companion object {
fun <T> success(data: T?): Resource<T> {
return Resource(
Status.SUCCESS,
data,
null
)
}
fun <T> error(message: String): Resource<T> {
return Resource(
Status.ERROR,
null,
message
)
}
fun <T> loading(): Resource<T> {
return Resource(
Status.LOADING,
null,
null
)
}
}
}
UnSplashPhotoUseCase.kt
class UnSplashPhotoUseCase @Inject constructor(
private val repository: UnSplashRepository
) : UseCaseWithParams<String,Resource<Flow<PagingData<UnsplashPhoto>>>>(){
override suspend fun buildUseCase(params: String): Resource<Flow<PagingData<UnsplashPhoto>>> {
return repository.getSearchResult(query = params)
}
}
UnSplashRepositoryImpl.kt
class UnSplashRepositoryImpl @Inject constructor(
private val networkManager: NetworkManager,
private val unsplashApi: UnsplashApi,
private val unSplashMapper: UnSplashMapper
) : UnSplashRepository{
override suspend fun getSearchResult(query: String): Resource<Flow<PagingData<UnsplashPhoto>>> {
return if(networkManager.isNetworkAvailable()){
try {
val pagingDataFlow = Pager(
config = PagingConfig(
pageSize = 20,
maxSize = 100,
enablePlaceholders = false
),
pagingSourceFactory = { UnsplashPagingSource(unsplashApi, query) }
).flow
Resource.success(pagingDataFlow)
} catch (exception:Exception){
Resource.error("")
}
} else Resource.error("Internet Not Available")
}
}
或者有没有更好的方法来处理网络和其他异常并将数据映射到我的类型
在 UnSplashRepositoryImpl.kt 我想返回Resource<Flow<PagingData<PhotoBO>>>