我试图使用存储库和服务定位器制作 mvvm 模式以使用模拟或远程调用,这取决于风格。
现在发生的事情是,在我收到服务器的响应后,我的 liveData 没有更新。所以现在我总是有一个空列表。
我使用这个谷歌示例来尝试制作它。
sample
下面我的代码,使用远程 serviceLocator
感谢您的帮助。

class TestActivity : AppCompatActivity(){

private val viewModel = TestViewModel(ServiceLocator.provideTasksRepository())
private lateinit var  binding : TestBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.test)
    binding.viewmodel = viewModel

    setupRecyclerView()
}

private fun setupRecyclerView() {
    binding.viewmodel?.run {
        binding.recyclerViewTest.adapter = TestAdapter(this)
    }
}
}
class TestAdapter(private val viewModel : TestViewModel) : ListAdapter<ResponseEntity, TestAdapter.TestViewHolder>(TestDiffCallback()) {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = TestViewHolder.from(parent)

override fun onBindViewHolder(holder: TestViewHolder, position: Int) {
    val item = getItem(position)
    holder.bind(viewModel, item)
}

class TestViewHolder private constructor(val binding: ItemTestBinding) :
    RecyclerView.ViewHolder(binding.root) {

    fun bind(viewModel: TestViewModel, item: ResponseEntity) {

        binding.viewmodel = viewModel
        binding.game = item
        binding.executePendingBindings()
    }

    companion object {
        fun from(parent: ViewGroup): TestViewHolder {
            val layoutInflater = LayoutInflater.from(parent.context)
            val binding = ItemTestBinding.inflate(layoutInflater, parent, false)

            return TestViewHolder(binding)
        }
    }
}
}
<?xml version="1.0" encoding="utf-8"?>
<data>

    <import type="android.view.View" />

    <import type="androidx.core.content.ContextCompat" />

    <variable
        name="game"
        type="com.test.ResponseEntity" />

    <variable
        name="viewmodel"
        type="com.test.TestViewModel" />

</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view_test"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:items="@{viewmodel.items}"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
class MyRepository(private val testRemoteDataSource: IDataSource) :
ITestRepository {

override suspend fun getList() = testRemoteDataSource.getList()
}
class TestViewModel(private val testRepository: MyRepository) : ViewModel() {

private var _items = MutableLiveData<List<ResponseEntity>>()
val items: LiveData<List<ResponseEntity>> = _items

init {
    refreshList()
}

private fun refreshList() {
    viewModelScope.launch {
        _items = testRepository.getList()
    }
}
}
object ServiceLocator {

var testRepository: MyRepository? = null

fun provideTasksRepository(): MyRepository {
    synchronized(this) {
        return testRepository ?: createTestRepository()
    }
}

private fun createTestRepository(): MyRepository {
    val newRepo = MyRepository(
        MyRemoteDataSource(RetrofitClient.apiInterface)
    )
    testRepository = newRepo
    return newRepo
}
}
class MyRemoteDataSource(private val retroService: IService) :
IDataSource {

private var responseEntityLiveData: MutableLiveData<List<ResponseEntity>> =
    MutableLiveData<List<ResponseEntity>>()

override suspend fun getGames(): MutableLiveData<List<ResponseEntity>> {

    retroService.getList()
        .enqueue(object : Callback<List<ResponseEntity>> {
            override fun onFailure(
                call: Call<List<ResponseEntity>>,
                t: Throwable
            ) {
                responseEntityLiveData.value = emptyList()
            }

            override fun onResponse(
                call: Call<List<ResponseEntity>>,
                response: Response<List<ResponseEntity>>
            ) {
                responseEntityLiveData.value = response.body()
            }
        })

    return responseEntityLiveData
}
}

最佳答案

我的猜测是,将 Coroutines 挂起功能与 Retrofit 和 LiveData 混合会导致一些副作用。
我没有单一的解决方案,但有些要点可以帮助您。
一般来说,我会避免将 LiveData 与挂起函数混合使用。 LiveData 是为 UI/ViewModel 层缓存数据的概念。下层不需要知道像 LiveData 这样的 Android 具体东西。 More information here
在您的存储库或数据源中,可以使用返回单个值的挂起函数或可以发出多个值的协程流。在您的 ViewModel 中,您可以将这些结果映射到您的 LiveData。
数据源
在您的数据源中,您可以使用 suspendCoroutinesuspendCancellableCoroutine 将 Retrofit(或任何其他回调接口(interface))与协程连接:

class DataSource(privat val retrofitService: RetrofitService) {

    /**
     * Consider [Value] as a type placeholder for this example
     */
    fun suspend fun getValue(): Result<Value> = suspendCoroutine { continuation ->
      retrofitService.getValue().enqueue(object : Callback<Value> {
        override fun onFailure(call: Call<List<ResponseEntity>>,
                               throwable: Throwable) {
          continuation.resume(Result.Failure(throwable)))
        }

        override fun onResponse(call: Call<List<ResponseEntity>>,
                                response: Response<List<ResponseEntity>>) {
          continuation.resume(Result.Success(response.body()))
        }
      }
   }
}
结果包装器
您可以将响应包装为您自己的 Result 类型,例如:
sealed class Result<out T> {

    /**
     * Indicates a success state.
     */
    data class Success<T>(val data: T) : Result<T>()

    /**
     * Indicates an error state.
     */
    data class Failure(val throwable: Throwable): Result<Nothing>
}
我从这个例子中去掉了 Repository,直接调用了 DataSource。
View 模型
现在在您的 ViewModel 中,您可以启动协程,获取 Result 并将其映射到 LiveData。
class TestViewModel(private val dataSource: DataSource) : ViewModel() {
    private val _value = MutableLiveData<Value>>()
    val value: LiveData<Value> = _value

    private val _error = MutableLiveData<String>()
    val error: LiveData = _error

    init {
        getValue()
    }

    private fun getValue() {
      viewModelScope.launch {
        val result: Result<Value> = dataSource.getValue()

        // check wether the result is of type Success or Failure
        when(result) {
          is Result.Success -> _value.postValue(result.data)
          is Result.Failure -> _error.value = throwable.message
        }
      }
    }
}
我希望对你有所帮助。

关于带有服务定位器的 Android MVVM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/65379854/

10-13 04:13