使用Kotlin进行抽象的改造调用未调用onChange

时间:2019-10-15 15:18:25

标签: android kotlin retrofit2

我想抽象化改造调用,因此在需要时不需要编写相同的样板代码。

抽象

open class NetworkCall<T> {
    lateinit var call: Call<T>
    var result: MutableLiveData<Resource<T>> = MutableLiveData()

    fun makeCall(call: Call<T>) {
        this.call = call
        val callBackKt = CallBackKt<T>()
        callBackKt.result.value = Resource.loading(null)
        this.call.enqueue(callBackKt)
        result = callBackKt.result
    }

    class CallBackKt<T> : Callback<T> {
        var result: MutableLiveData<Resource<T>> = MutableLiveData()

        override fun onFailure(call: Call<T>, t: Throwable) {
            result.value = Resource.error()//APIError()
            t.printStackTrace()
        }

        override fun onResponse(call: Call<T>, response: Response<T>) {
            if (response.isSuccessful) {
                result.value = Resource.success(response.body())
            }
            else {
                result.value = Resource.error()
            }
        }
    }
}

存储库

class DetailsRepository(val application: Application) {
    private val myListDao =
        AppDatabase.getDatabase(application)?.MyListDao()
    var movie: MutableLiveData<Resource<DetailsDTO>> = MutableLiveData()

    fun getDetails(id: Int) {
        val networkCall = NetworkCall<DetailsDTO>()
        networkCall.makeCall(Apifactory.tmdbApi.getDetails(id))
        movie = networkCall.result
    }
}

ViewModel

class DetailsViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: DetailsRepository = DetailsRepository(application)
    internal var movie: LiveData<Resource<DetailsDTO>> = repository.movie

    fun insert(myListItem: MyListItem) {
        repository.insert(myListItem)
    }

    fun fetchDetails(id: Int) {
        repository.getDetails(id)
    }

}

活动

 viewModel.movie.observe(this, Observer {
            it?.apply {
                detail_title.text = data?.title
            }
        })

在每种方法中登录均表示已按正确的顺序调用该方法,并且该请求正常运行。没有调用Althoght onChange。

fetchDetails called
getDetails called
makeCall called
onResponse successful, result.value.data = DetailsDTO(adult=false, backdrop_path=/y8lEIjYZCi2VFP4ixtHSn2klpth.jpg, ... 
...

怎么办?

0 个答案:

没有答案