【发布时间】:2022-01-06 12:40:05
【问题描述】:
我正在从 Unsplash api 实现搜索,数据将在搜索的基础上更新
GalleryViewModel.kt
@HiltViewModel
class GalleryViewModel @Inject constructor(
private val fetchPhotoUseCase:FetchPhotoUseCase,
@Assisted state: SavedStateHandle
) :ViewModel(){
companion object{
private const val CURRENT_QUERY = "current_query" // key
private const val DEFAULT_QUERY = "cats"
}
private val currentQuery = state.getLiveData(CURRENT_QUERY, DEFAULT_QUERY)
val photos = currentQuery.switchMap { queryString ->
liveData {
fetchPhotoUseCase.execute(queryString).collect {
emit(it)
}
}
}
fun searchPhotos(query: String) {
currentQuery.value = query
}
}
FetchPhotoUseCase.kt
class FetchPhotoUseCase @Inject constructor(
private val repository: UnSplashRepository
) : UseCaseWithParams<String,Flow<PagingData<UnsplashPhoto>>>(){
override suspend fun buildUseCase(params: String): Flow<PagingData<UnsplashPhoto>> {
return repository.getSearchResult(params)
}
}
FetchPhotoUseCase 在域层中。它返回流,因此我将流更改为 switchmap lambda 中的实时数据。
我做得对还是有更好的方法来实现它..
编辑
我已经更新了我的代码,可以在下面的两个调度程序上工作..
suspend fun getPhotos(queryString: String) = withContext(Dispatchers.IO){
fetchPhotoUseCase.execute(queryString)
}
fun getImages(queryString: String) = liveData(Dispatchers.Main) {
getPhotos(queryString).collect {
emit(
it.map { unsplash ->
unSplashMapper.mapFromEntity(unsplash)
}
)
}
}
【问题讨论】:
标签: android kotlin kotlin-coroutines android-livedata kotlin-flow