android - MVVM 我应该从哪里订阅 Rx?
问题描述
我来自MVP
模式,现在我正在使用MVVM
模式和 RXJava 来执行一些功能,例如在地图中显示我当前的位置。为此,我在我的 MV 中订阅 aDisposable
并且我会得到一个Location
:(t
是我的位置)
val subscription = locationProvider.lastKnownLocation
.subscribe(Consumer { t -> updateLocationMap(t) })
我的问题是我应该Disposable
在我的View
? 因为我看到ViewModel
不能在 中实例化View
并且知道我不知道如何使用这个Location
对象。
解决方案
这是一个例子
在 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
})
推荐阅读
- javascript - 带有状态的 ifElse 语句?
- android - 如何使用可绘制的形状制作如下图所示的形状?
- docusignapi - DocuSign Rest API 替换单个模板文档
- scala - spark scala中数据框列与其数组之间的总和不同
- java - 从 Web 逻辑服务器发布的重复肥皂请求以响应接收超时
- php - 找出两个表之间的差异
- swift - 结合 flatMap/Scan 携带中间结果
- regex - 在 spark 数据框中为包含 , 的列名加上引号
- python - RuntimeError:无法使用 ThreadPool 启动新线程并且只有少数线程
- javascript - tinyMCE 本地安装不适用于本地 js 文件,但可以使用远程 js 文件