将分页数据流映射到另一个模型



我创建了一个用于学习的图库应用程序。图像是从不同的来源获取的,如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>>>

是的,你可以映射Flow<PagingData<UnsplashPhoto>>,这里应该没有问题,你只需要两个maps:

Resource.success(pagingDataFlow.map { pagingData ->
pagingData.map { unsplashPhoto -> PhotoBO(unsplashPhoto) }
})

相关内容

  • 没有找到相关文章

最新更新