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

标签 android kotlin kotlin-coroutines android-livedata kotlin-flow

我正在从 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)
                }
            )
        }
    }

最佳答案

有一个方便的方法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"

关于android - 将流量转换为实时数据的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70607233/

相关文章:

kotlin - 如何向 kotlin 协程发出 postman 请求

android - Gradle 尝试从错误的存储库下载

android - 为什么 findViewById 对于 CardView 返回 null?

android - 在 android 中扩展 LinearLayout 而不是 Activity

android - 如何使用OnLongClickListener更改ImageView图像以及如何使用Kotlin保存状态

spring-boot - Spring-Boot 是否处理 WebFlux 上下文之外的 Kotlin 协程?

spring - 如何避免在执行长时间运行计算的 Spring WebFlux Controller 中使用 Kotlin Coroutines 的 GlobalScope

java - 由于 NPE 恢复 Activity 时发生崩溃

java - kotlin.TypeCastException : null cannot be cast to non-null type android. 图形.Bitmap

android - Kotlin Retrofit response.body() 返回 null