单击ui时,我试图刷新我的ViewModel中的LiveData。但是,我不知道如何。我正在尝试重置DataSource.Factory,然后使其无效,但它仍然从第一次加载相同的网络调用。
ViewModel:
class RedditViewModel @Inject constructor(val redditService: LedditService,
val sharedPrefsManager: SharedPrefsManager): ViewModel() {
private val subredditName = MutableLiveData<String>()
private var dataSourceFactory = TopicDataSourceFactory(redditService, sharedPrefsManager.lastSubreddit)
private val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(30)
.setInitialLoadSizeHint(60)
.build()
var topicList = switchMap(subredditName) {LivePagedListBuilder<String, Children<Topic>>(dataSourceFactory, config).build()}
fun switchSub(sub: String){
if(subredditName.value != sub){
subredditName.value = sub
sharedPrefsManager.lastSubreddit = sub
dataSourceFactory = TopicDataSourceFactory(redditService, sharedPrefsManager.lastSubreddit)
dataSourceFactory.postData.value?.invalidate()
}
}
}
TopicDataSourceFactory:
class TopicDataSourceFactory(private val service: LedditService,
private val subredditName: String): DataSource.Factory<String, Children<Topic>>() {
val postData = MutableLiveData<TopicPageKeyedDataSource>()
override fun create(): DataSource<String, Children<Topic>> {
val dataSource = TopicPageKeyedDataSource(service, subredditName)
postData.postValue(dataSource)
return dataSource
}
}