我正在使用以下ViewModel:
library(shiny)
library(shinydashboard)
# UI1 ####
ui1 <- fluidPage(
textInput('password', label = 'Say hello')
)
# UI2 ####
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody()
ui2 <- dashboardPage(header, sidebar, body)
# Server ####
server <- function(input, output){
status <- reactiveValues(logged = F)
observeEvent(input$password,{
if(input$password == 'hello'){
status$logged <- T
}
})
output$uipage <- renderUI({
if(status$logged){
ui2
} else {
ui1
}
})
}
# UI ####
ui <- uiOutput("uipage")
shinyApp(ui = ui, server = server)
}
我在Fragment中以这种方式观察 feed :
public class FeedViewModel extends ViewModel {
private final MutableLiveData<Photo> selectedPhoto = new MutableLiveData<>();
private final FeedRepository repository;
private LiveData<Resource<List<Photo>>> feed;
@Inject
FeedViewModel(@NonNull final FeedRepository repository) {
this.repository = repository;
}
public void selectPhoto(@NonNull final Photo photo) {
selectedPhoto.setValue(photo);
}
public LiveData<Photo> getSelectedPhoto() {
return selectedPhoto;
}
LiveData<Resource<List<Photo>>> getUserFeed() {
if (feed == null) {
feed = new MutableLiveData<>();
feed = repository.get();
}
return feed;
}
@Override
protected void onCleared() {
super.onCleared();
}
问题是:如何以正确的方式刷新 Feed ?假设用户触发了swipeToRefresh,因此该事件必须创建一个feed的刷新任务。我如何使用ViewModel实现这一点?
答案 0 :(得分:1)
您必须使用liveData.post(新数据)
获取数据并更新实时数据InActivity:
//to be called on refresh data
vieeModel.getLatestFeed()
In View Model:
fun getLatestFeed() {
//get data from repository
feed.post(refreshedData)
}
答案 1 :(得分:1)
您可以使用“loadTrigger”来触发数据加载,当滑动刷新时。
将此代码添加到您的片段中:
viewModel.userFeeds.observe(
//add observation code
)
swipToRefresh.setOnRefreshListener {
viewModel.loadFeeds()
}
在视图模型中:
val loadTrigger = MutableLiveData(Unit)
val userFeeds = loadTrigger.switchMap {
repository.get()
}
fun loadFeeds() {
loadTrigger.value = Unit
//livedata gets fired even though the value is not changed
}
这里建议的解决方案是: manual refresh without modifying your existing LiveData
我对其进行了测试,效果很好。