我正在尝试获取观察值中的数据,但是它不起作用,因为在订阅中触发了“ postvalue”方法后数据没有到达。我在做什么错了?
片段
private fun initMapRoutes(mapRoutes: RecyclerView) {
val m1 = MapRoute("1", "#ff00dd")
val mapRouteAdapter = MapRouteAdapter(arrayOf(m1))
mapRoutes.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
mapRoutes.adapter = mapRouteAdapter
val viewModel = ViewModelProviders.of(activity!!).get(OnlineTagiltramViewModel::class.java)
viewModel.getMapTrams().observe(this, Observer { data -> onMapTramsReceived(data) })
viewModel.loadMapTrams()
}
fun onMapTramsReceived(data: List<MapTram>?) {
if (data == null || data.isEmpty()) {
return
}
}
在视图模型中
private var onlineTagiltramInteractor: OnlineTagiltramInteractor? = null
private var onlineTagiltramDisposable: Disposable? = null
val mapTrams: MutableLiveData<List<MapTram>> = MutableLiveData()
fun getMapTrams() : LiveData<List<MapTram>> {
return mapTrams
}
init {
this.onlineTagiltramInteractor = OnlineTagiltramInteractor()
}
fun loadMapTrams() {
removeDisposable(onlineTagiltramDisposable)
onlineTagiltramDisposable = onlineTagiltramInteractor
?.loadData()?.subscribe( { data -> mapTrams.postValue(data) },
{throwable -> Log.e("s", throwable.message)})
addDisposable(onlineTagiltramDisposable!!)
}
在交互器中
class OnlineTagiltramInteractor {
fun loadData() : Flowable<List<MapTram>> {
val api = RetrofitFactory.instance.onlineTagiltramApiService
return Flowable.interval(2, TimeUnit.SECONDS)
.observeOn(Schedulers.io())
.flatMap { api.getMapTrams() }
}
onMapTramsReceived方法未调用