LiveData returns 错误的对象

LiveData returns wrong Object

我将 Hilt 添加到我的项目中,现在 LiveData returns 错误 Object type。也许我在代码中做了一些错误的更改。 getAllCurrencies returns LiveData<Resource<Unit>> 但它应该 LiveData<Resource<Currencies>>

视图模型:

class SplashScreenViewModel @ViewModelInject constructor(
private val roomDatabaseRepository: RoomDatabaseRepository,
private val retrofitRepository: RetrofitRepository) : ViewModel() {

fun getAllCurrencies(mainCurrency: String) = liveData(Dispatchers.IO) {
       emit(Resource.loading(data = null))
        try {
            emit(Resource.success(data = retrofitRepository.getAllCurrencies(mainCurrency)))
        } catch (exception: Exception) {
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

存储库:(returns 好类型)

class RetrofitRepository @Inject constructor(val currenciesApiHelper: CurrenciesApiHelper) {

suspend fun getAllCurrencies(mainCurrency: String) {
  currenciesApiHelper.getAllCurrencies(mainCurrency)
}

您应该 return currenciesApiHelper.getAllCurrencies(mainCurrency) 进入存储库。


(可选)以下是我使用 MVVM 的方式:

我假设您已经在某处声明了 Currency 作为模型。

状态

sealed class Status<out T> {
    class Loading<out T> : Status<T>()
    data class Success<out T>(val data: T) : Status<T>()
    data class Failure<out T>(val exception: Exception) : Status<T>()
}

Fragment/Presentation层

viewModel.fetchCurrencies(mainCurrency)
            .observe(viewLifecycleOwner, Observer { result ->
                when (result) {
                    is Status.Loading<*> -> {
                        //display a ProgressBar or so
                    }

                    is Status.Success<*> -> {
                        //Status.Success<*> can also be Status.Success<ArrayList<Currency>>
                        //hide the ProgressBar
                        val currencies = result.data as ArrayList<Currency> 
                    }

                    is Status.Failure<*> -> {
                        //log the exception
                    }
                }
            })

ViewModel

private val repo = Repository()

@ExperimentalCoroutinesApi
    fun fetchCurrencies(mainCurrency: String): LiveData<Status<MutableList<Currency>>> =
        liveData(Dispatchers.IO) {
            emit(Status.Loading())

            try {
                repo.getCurrencies(mainCurrency).collect {
                    emit(it)
                }

            } catch (e: Exception) {
                emit(Status.Failure(e))
                Log.e("ERROR:", e.message!!)
            }
        }

存储库(单一数据源)

这里改用 Firestore,因为我不是 100% 肯定你的方式。

retrofitRepository.getAllCurrencies(mainCurrency)应该做的,然后给出结果。

private val fs: FirebaseFirestore = Firebase.firestore

@ExperimentalCoroutinesApi
    fun getCurrencies(mainCurrency: String): Flow<Status<MutableList<Currency>>> = callbackFlow {

        val subscription = fs.collection("currencies")
            .addSnapshotListener { snapshot, _ ->
                if (snapshot != null) {
                    val result = snapshot.toObjects(Currency::class.java)
                    offer(Success(result))
                }
            }

        awaitClose { subscription.remove() }
    }

顺便说一下,使用协同程序非常棒。看这里:

Learn advanced coroutines with Kotlin Flow and LiveData

Android Coroutines: How to manage async tasks in Kotlin

希望对您有所帮助:)