Skip to content

Instantly share code, notes, and snippets.

@haidar786
Created February 7, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haidar786/dc17dd768b3f71dfa8fe58df860e278b to your computer and use it in GitHub Desktop.
Save haidar786/dc17dd768b3f71dfa8fe58df860e278b to your computer and use it in GitHub Desktop.
package com.cinderellaman.live.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.cinderellaman.live.youtubeapi.search.State
import com.cinderellaman.live.youtubeapi.search.datasource.SearchDataSource
import com.cinderellaman.live.youtubeapi.search.datasource.SearchDataSourceFactory
import com.cinderellaman.live.youtubeapi.search.network.NetworkService
import com.cinderellaman.live.youtubeapi.search.response.Item
import io.reactivex.disposables.CompositeDisposable
class MainViewModel(application: Application) : AndroidViewModel(application) {
//paging
private val networkService = NetworkService.getService()
var searchList: LiveData<PagedList<Item>>
private val compositeDisposable = CompositeDisposable()
private val pageSize = 50
private val searchDataSourceFactory: SearchDataSourceFactory
init {
//paging
searchDataSourceFactory = SearchDataSourceFactory(compositeDisposable, networkService)
val config = PagedList.Config.Builder()
.setPageSize(pageSize)
.setInitialLoadSizeHint(pageSize)
.setEnablePlaceholders(false)
.build()
searchList = LivePagedListBuilder<String, Item>(searchDataSourceFactory, config).build()
}
fun getState(): LiveData<State> = Transformations.switchMap<SearchDataSource,
State>(searchDataSourceFactory.searchDataSourceLiveData,SearchDataSource::state)
fun retry() {
searchDataSourceFactory.searchDataSourceLiveData.value?.retry()
}
fun setQuery(query: String){
searchList.value?.dataSource?.invalidate()
}
override fun onCleared() {
super.onCleared()
compositeDisposable.dispose()
}
fun listIsEmpty(): Boolean {
return searchList.value?.isEmpty() ?: true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment