我将 Hilt 添加到我的项目中,现在
LiveData
返回错误 Object type
。也许我对代码做了一些错误的更改。
getAllCurrencies
返回 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!"))
}
}
存储库:(它返回良好的类型)
class RetrofitRepository @Inject constructor(val currenciesApiHelper: CurrenciesApiHelper) {
suspend fun getAllCurrencies(mainCurrency: String) {
currenciesApiHelper.getAllCurrencies(mainCurrency)
}
您应该
return currenciesApiHelper.getAllCurrencies(mainCurrency)
进入存储库。
(可选)以下是我使用 MVVM 的方法:
我假设您已经在某处声明了货币作为模型。
状态
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>()
}
片段/表示层
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
}
}
})
视图模型
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() }
}
使用协程是相当不错的。看看这里:
使用 Kotlin Flow 和 LiveData 学习高级协程
希望有帮助:)
2024 年这仍然有效吗?