我正在Kotlin中实现一个Android应用程序,该应用程序使用API作为数据的主要来源。我使用Kotlin,RXjava,Retrofit和Dagger使其正常工作。
但是由于某种原因,我在onNext函数上的人员对象为空。即使我在Logcat中看到了http方法调用数据,并且它具有正确的person对象。
我正在从JSON请求人员对象:
{
"persons": [{
"personId": 1,
"personName": "Bert",
"personAge": 19,
"isFemale": "false",
"birthDate": "2000-06-28T00:00:00"
}
]
}
ApiInterface:
@GET("persons")
fun getPerson(@Query("personId") personId: Int): Observable<Person>
PersonRepository:
class PersonRepository @Inject constructor(val apiInterface: ApiInterface) {
fun getPerson(personId: Int): Observable<Person>{
return apiInterface.getPerson(personId)
}
}
人员ViewModel:
class PersonViewModel @Inject constructor(private val personRepositoy: PersonRepository) : ViewModel() {
var personResult: MutableLiveData<Person> = MutableLiveData()
var personError: MutableLiveData<String> = MutableLiveData()
lateinit var disposableObserver: DisposableObserver<Person>
fun personResult(): LiveData<Person> {
return personResult
}
fun personError(): LiveData<String> {
return personError
}
fun loadPerson(personId: Int) {
disposableObserver: object : DisposableObserver<Person>() {
override fun onComplete() {}
override fun onNext(person: Person){ //this is empty for some reason
personResult.postValue(person)
}
override fun onError(e: Throwable) {
personError.postValue(e.message)
}
}
personRepository.getPerson(personId)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(disposableObserver)
}
fun disposeElements() {
if(null !- disposableObserver && !disposableObserver.isDisposed) {
disposableObserver.dispose()
}
}
}
进行呼叫的PersonActivity:
@Inject
lateinit var personViewModelFactory: PersonViewModelFactory
lateinit var personViewModel: PersonViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_person)
AndroidInjection.inject(this)
personViewModel = ViewModelProviders.of(this, personViewModelFactory).get(PersonViewModel::class.java)
personViewModel.loadPerson(1)
personViewModel.personResult().observe(this, Observer<Person> {
//some code that uses it
}
}
getPerson调用返回我可以在日志中看到的正确的人,但是它没有像我想要的那样将值发布到personResult中。我不知道为什么。
编辑:根据要求添加了Person类。请注意,@ Json是GSON中@SerializedName的Moshi等效项。
data class Person (
@Json(name = "personId")
val personId: Int,
@Json(name = "personName")
val name: String,
@Json(name = "personAge")
val age: Int,
@Json(name = "isFemale")
val isFemale: Boolean,
@Json(name = "birthDate")
val birthDate: GregorianCalendar
)
答案 0 :(得分:1)
为避免JSON响应与要使用的实际对象不匹配,请定义一个中间类,如下所示:
data class PersonResponse(
@Json(name = "persons")
val persons: List<Person>
)
示例api类:
@GET("persons")
fun getPerson(@Query("personId") personId: Int): Observable<PersonResponse>
@GET("persons")
fun getAllPersons(): Observable<PersonResponse>
示例存储库类:
fun getPerson(personId: Int): Observable<Person>{
// Convert PersonResponse -> Person
return apiInterface.getPerson(personId)
.doOnNext { value -> Log.d(SOME_LOG_TAG, "onNext: value=$value") }
.doOnError { error -> Log.d(SOME_LOG_TAG, "onNext: value=${e.getMessage()}") }
.flatMap { response ->
// Check if the list contains exactly one Person and throw error if it doesn't
if (response.persons.size == 1)
Observable.just(response.persons[0])
else
Observable.error(Throwable("Something's wrong"))
}
}
fun getAllPerson(): Observable<List<Person>> {
// Convert PersonResponse -> List<Person>
return apiInterface.getAllPersons()
.map { response -> response.persons }
}
如您所见,存储库代码看起来很混乱。我建议在api类和存储库类之间做一个中间层,以完成所有转换。