将流量转换为实时数据的最佳方式

best way to convert flow to live data

我正在从 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在领域层。它 returns 流所以我在 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)
                }
            )
        }
    }

有一个方便的方法 asLiveData,它已经实现了您所写的内容:

val photos = currentQuery.switchMap { queryString ->
    fetchPhotoUseCase.execute(queryString).asLiveData(Dispatchers.Main)
}

使用asLiveData()扩展函数的依赖:

def lifecycle_version = "2.4.0"

implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"