AndroidViewModel - он используется, когда вам нужен контекст, когда этот класс использовался другим классом, используемым классом ViewModel ().код ниже работает оба условия, если вы использовали androidviewmodel или viewmodel.
class UserViewModel : ViewModel() {
lateinit var userList: LiveData<PagedList<User>>
private val compositeDisposable = CompositeDisposable()
private val pageSize = 10
lateinit var sourceFactory: UsersDataSourceFactory
lateinit var productList:LiveData<PagedList<ProductsItem>>
var tDataSource: LiveData<ProductListSource>? = null
lateinit var productListSource:ProductDataSourceFactory
var networkState: LiveData<NetworkState>? = null
var productData: LiveData<Product>? = null
fun init(apiListener: ApiListener) {
sourceFactory = UsersDataSourceFactory(compositeDisposable, apiListener)
val config = PagedList.Config.Builder()
.setPageSize(pageSize)
.setEnablePlaceholders(false)
.build()
userList = LivePagedListBuilder<Long, User>(sourceFactory, config).build()
}
fun getProductData(apiListener: ApiListener){
productListSource= ProductDataSourceFactory(apiListener)
tDataSource = productListSource.mutableLiveData
networkState = Transformations.switchMap(productListSource.mutableLiveData) { dataSource -> dataSource.networkState }
productData = Transformations.switchMap(productListSource.mutableLiveData) { dataSource -> dataSource.productList }
val config=PagedList.Config.Builder()
.setInitialLoadSizeHint(5)
.setPageSize(pageSize)
.setEnablePlaceholders(false)
.build()
productList=LivePagedListBuilder<Long,ProductsItem>(productListSource,config).build()
}
override fun onCleared() {
super.onCleared()
compositeDisposable.dispose()
}
fun retryGetProduct() {
productListSource.mutableLiveData.value!!.retry()
}
fun retry() {
sourceFactory.usersDataSourceLiveData.value!!.retry()
}
fun refresh() {
sourceFactory.usersDataSourceLiveData.value!!.invalidate()
}
/ * fun getNetworkStateData (): LiveData = Transformations.switchMap (productListSource.mutableLiveData, {it.networkState})
fun getNetworkState(): LiveData<NetworkState> = Transformations.switchMap<UsersDataSource, NetworkState>(
sourceFactory.usersDataSourceLiveData, { it.networkState })
fun getRefreshState(): LiveData<NetworkState> = Transformations.switchMap<UsersDataSource, NetworkState>(
sourceFactory.usersDataSourceLiveData, { it.initialLoad })*/
}
доступ подобным образом ..
viewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)