使用Jackson和Retrofit的异步JSON映射

时间:2019-11-27 11:49:07

标签: android kotlin jackson retrofit android-livedata

我们使用存储库是为了通过ViewModel向活动提供信息。

我们使用Retrofit 2执行网络操作,并使用Jackson进行JSON映射。在存储库中如何执行此操作:

private fun getRemoteSuggestions(locale: String, term: String, pos: String): LiveData<Suggestions?> {
    val suggestionLiveData: MutableLiveData<Suggestions?> = MutableLiveData()

    if (request != null) {
        request?.cancel()
    }

    request = autocompleteService.fetch(locale, term, pos)
    request?.enqueue {
        onResponse = { response ->
            val payload = response.body()?.payload
            payload?.let {
                val suggestions = objectMapper().treeToValue(payload, Suggestions::class.java)
                if (suggestions.isEmpty()) {
                    suggestions.error = ServiceError(Errors.NO_DATA_FOUND)
                }
                if (waitingForTerm == term) suggestionLiveData.postValue(suggestions)
            } ?: run {
                if (waitingForTerm == term) suggestionLiveData.postValue(null)
            }
        }
        onFailure = { error ->
            Logger.d("Need to throw exception")
        }
    }
    return suggestionLiveData
}

据我们所知enqueue在后​​台线程中执行网络调用,但是onResponse在主线程中工作。 可以添加Anko doAsync{}吗?

private fun getRemoteSuggestions(locale: String, term: String, pos: String): LiveData<Suggestions?> {
    ...
        onResponse = { response ->
            doAsync {
                ...
            }
        }
    ...
}

此外,这是我们更新RecycleView的方式。

this.autocompleteViewModel.getSuggestions(term).observe(this, Observer {
    if (this.searchTriggered) return@Observer
    it?.let { suggestions ->
        val sections = autocompleteViewModel.getAutocompleteSections(term.length, suggestions)
        runOnUiThread {
            autocompleteAdapter?.add(sections)
        }
    }
})

您怎么看?有更好的解决方案吗?

0 个答案:

没有答案