-1

互联网上提供的大量示例使您感到困惑,一些教程仅返回 Domain Model ,一些 return LiveData<DomainModel>,还有一些 return Flow<DomainModel>。我知道这一点LiveData并且Flow是不同的,但是你什么时候应该返回常规域模型与那些像 LiveData、Flow、StateFlow、SharedFlow 等可观察的模型?有什么区别吗?

来自 Android Architecture 组件示例

**
 * Repository that handles User objects.
 */
@OpenForTesting
@Singleton
class UserRepository @Inject constructor(
    private val appExecutors: AppExecutors,
    private val userDao: UserDao,
    private val githubService: GithubService
) {

    fun loadUser(login: String): LiveData<Resource<User>> {
        return object : NetworkBoundResource<User, User>(appExecutors) {
            override fun saveCallResult(item: User) {
                userDao.insert(item)
            }

            override fun shouldFetch(data: User?) = data == null

            override fun loadFromDb() = userDao.findByLogin(login)

            override fun createCall() = githubService.getUser(login)
        }.asLiveData()
    }
}

一些教程

class UseCase @Inject constructor(
    private val repository: Repo
) {
    operator fun invoke(someparam: String): Flow<Resource<DomainModel>> = flow {
        try {
            emit(Resource.Loading<DomainModel>())
            val sample= repository.getSample(someparam)
            emit(Resource.Success<DomainModel>(sample))
        } catch(e: HttpException) {
            emit(Resource.Error<DomainModel>(e.localizedMessage ?: "An unexpected error occured"))
        } catch(e: IOException) {
            emit(Resource.Error<DomainModel>("Couldn't reach server. Check your internet connection."))
        }
    }
}

另一个教程

class RecipeRepository_Impl (
        private val service: SomeService,
        private val mapper: SomeMapper,
): RecipeRepository {

    override suspend fun search(param: String): List<DomainModel> {
        return mapper.toDomainList(service.search(param))
    }

    override suspend fun get(param: String): DomainModel{
        return mapper.mapToDomainModel(service.get(param))
    }

}

我不是在问LiveDatavs Flow,这个问题显然与何时使用常规域模型对象与可观察对象有关。在什么情况和情况下。

4

0 回答 0