首页 > 解决方案 > MVVM 我应该从哪里订阅 Rx?

问题描述

我来自MVP模式,现在我正在使用MVVM模式和 RXJava 来执行一些功能,例如在地图中显示我当前的位置。为此,我在我的 MV 中订阅 aDisposable并且我会得到一个Location:(t是我的位置)

val subscription = locationProvider.lastKnownLocation
    .subscribe(Consumer { t -> updateLocationMap(t) })

我的问题是我应该Disposable在我的View? 因为我看到ViewModel不能在 中实例化View并且知道我不知道如何使用这个Location对象。

标签: androidmvvmrx-javasystem.reactiveandroid-livedata

解决方案


这是一个例子

在 Viewmodel 中创建变量

    val LocationLiveData = MutableLiveData<Location>()

下面的代码应该在视图模型中

 disposable = locationProvider.lastKnownLocation
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe{location -> 
                LocationLiveData.postValue(location)
            }

之后在 View( Activity )

 viewmodel.LocationLiveData.observe(this, { t: Location? -> 
   //use this updated location
  }) 

推荐阅读