我无法将Retrofit与MVVM体系结构链接。确实,在阅读了文档之后,他们只讨论了用于SQLite本地数据库的Room,我进行了相同的搜索,但搜索了来自Rest Server的数据。 所以,我试图做类似的事情,但没有成功: https://proandroiddev.com/mvvm-architecture-viewmodel-and-livedata-part-1-604f50cda1
我有一个观察ViewModel的活动:
活动代码:
mFlightPlanViewModel = ViewModelProviders.of(this).get(FlightPlanViewModel.class);
mFlightPlanViewModel.getFlightPlans().observe(this, (flightPlans) -> {
Log.d(TAG, "ON_CHANGED");
mFlightPlanAdapter.setFlightPlans(flightPlans);
});
ViewModel:
public class FlightPlanViewModel extends AndroidViewModel {
private static final String TAG = "FlightPlanViewModel";
private LiveData<List<FlightPlan>> mFlightPlans;
private FlightPlanRepository mFlightPlanRepository;
public FlightPlanViewModel(@NonNull Application application) {
super(application);
Log.d(TAG, "CONSTRUCTOR");
mFlightPlanRepository = FlightPlanRepository.getInstance();
mFlightPlans = mFlightPlanRepository.getFlightPlans();
}
public LiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
return mFlightPlans;
}
}
ViewModel回答使用单例模式的存储库:
public class FlightPlanRepository {
private static final String TAG = "FlightPlanRepository";
private static FlightPlanRepository instance;
private RestApi mRestApi;
private FlightPlanRepository() {
Log.d(TAG, "CONSTRUCTOR");
mRestApi = RestDao.getRestDao();
}
public static FlightPlanRepository getInstance() {
Log.d(TAG, "GET_INSTANCE");
if (instance == null) {
instance = new FlightPlanRepository();
}
return instance;
}
public MutableLiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
@Override
public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
if (response.code() == 200) {
List<FlightPlan> temp = response.body();
for (FlightPlan flightPlan : temp) {
Log.d(TAG + "res", flightPlan.toString());
}
data.setValue(response.body());
Log.d(TAG + "res", response.toString());
}
}
@Override
public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
List<FlightPlan> flightPlans = new ArrayList<>();
flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
data.setValue(flightPlans);
Log.d(TAG, t.getMessage());
}
});
return data;
}
}
存储库使用Retrofit实例:
public class RestDao {
private static final String BASE_URL = "http://192.168.1.78:8080";
private static Retrofit instance;
private static Retrofit getInstance() {
if (instance == null) {
instance = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return instance;
}
public static RestApi getRestDao() {
return getInstance().create(RestApi.class);
}
}
它使用此界面:
public interface RestApi {
@GET("/plan/list")
Call<List<FlightPlan>> getFlightPlanList();
}
部分无效的代码是:
public MutableLiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
@Override
public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
if (response.code() == 200) {
List<FlightPlan> temp = response.body();
for (FlightPlan flightPlan : temp) {
Log.d(TAG + "res", flightPlan.toString());
}
data.setValue(response.body());
Log.d(TAG + "res", response.toString());
}
}
@Override
public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
List<FlightPlan> flightPlans = new ArrayList<>();
flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
data.setValue(flightPlans);
Log.d(TAG, t.getMessage());
}
});
return data;
}
这将返回一个空列表。我想我明白为什么:调用enqueue()方法发出的请求在另一个线程中,因此在这里我们返回数据而无需等待结果。
所以我的问题是如何链接Retrofit和ViewModel?
答案 0 :(得分:0)
凯文(Kevin)只是对您的代码进行了微小的更改。而不是MutableLiveData从存储库返回LiveData:
library(seqinr)
library(shiny)
# User interface
ui <- fluidPage(
titlePanel("Welcome to DotMatcher Plot App"),
sidebarLayout(
sidebarPanel (
fileInput("protein1",
label = "Choose a file",
multiple = FALSE,
accept =c("text", "fasta")),
fileInput( "protein2",
label = NULL,
multiple=FALSE,
accept =c("text", "fasta"))
),
# Outputs
mainPanel(
plotOutput(outputId = "plot")
)
)
)
# Server Function
server <- function(input, output) {
seq1 <- reactive({
req(s2c(paste(input$protein1, collapse = "")})
seq2 <- reactive({
req(s2c(paste(input$protein2, collapse = "")
})
output$plot <- renderPlot({
dotPlot(seq1(), seq2(), wsize = 100, wstep = 100, nmatch = 100)
})
}
# App
shinyApp(ui = ui, server = server)
答案 1 :(得分:0)
如果我这样做:
public LiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
List<FlightPlan> flightPlans = new ArrayList<>();
flightPlans.add(new FlightPlan(5, "Test5", 3.551, 50.52, 3.55122, 50.52625));
data.setValue(flightPlans);
Log.d(TAG, data.getValue().toString());
mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
@Override
public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
if (response.code() == 200) {
List<FlightPlan> temp = response.body();
for (FlightPlan flightPlan : temp) {
Log.d(TAG + "res", flightPlan.toString());
}
data.setValue(response.body());
Log.d(TAG + "res", response.toString());
}
}
@Override
public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
List<FlightPlan> flightPlans = new ArrayList<>();
flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
data.setValue(flightPlans);
Log.d(TAG, t.getMessage());
}
});
return data;
}
我可以在Logcat中看到默认值,两个值来自我的rest服务器,但是字符串是空值,并且int / doubles为0,并且不会将这两个rest条目添加到回收器视图中。 / p>
这是我的活动代码:
public class FlightPlanActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, LifecycleOwner {
private static final String TAG = "FlightPlanActivity";
private FlightPlanAdapter mFlightPlanAdapter;
private FlightPlanViewModel mFlightPlanViewModel;
/**
* UI
*/
private FloatingActionButton mAddPlanButton;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_flight_plan);
Log.d(TAG, "onCreate called");
initUI();
}
private void initUI() {
this.setTitle("Flight Plans");
mRecyclerView = findViewById(R.id.flight_plan_list);
mAddPlanButton = findViewById(R.id.add_flight_plan);
mSwipeRefreshLayout = findViewById(R.id.refresh_flight_plan_list);
mAddPlanButton.setOnClickListener(this);
mSwipeRefreshLayout.setOnRefreshListener(this);
mFlightPlanAdapter = new FlightPlanAdapter();
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mFlightPlanAdapter);
mFlightPlanViewModel = ViewModelProviders.of(this).get(FlightPlanViewModel.class);
mFlightPlanViewModel.getFlightPlans().observe(this, (flightPlans) -> {
Log.d(TAG, "ON_CHANGED");
mFlightPlanAdapter.setFlightPlans(flightPlans);
});
}
@Override
public void onClick(View v) {
if (v.getId() == mAddPlanButton.getId()) {
// TODO: A implémenter
}
}
@Override
public void onRefresh() {
mFlightPlanAdapter.setFlightPlans(mFlightPlanViewModel.getFlightPlans().getValue());
mSwipeRefreshLayout.setRefreshing(false);
}
}
答案 2 :(得分:0)
那么,如果我做出回应,会发生什么?
public LiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
@Override
public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
if (response.code() == 200) {
data.setValue(response.body());
}
}
@Override
public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
// Do something
}
});
return data;
}
我运行该命令,首先有一个空对象返回,但是如果有响应,它将返回一些东西吗?
我尝试过:
public LiveData<List<FlightPlan>> getFlightPlans() {
Log.d(TAG, "GET_FLIGHT_PLANS");
MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
List<FlightPlan> flightPlans;
try {
Response<List<FlightPlan>> response = mRestApi.getFlightPlanList().execute();
if (response.isSuccessful()) {
flightPlans = response.body();
} else {
Log.d(TAG, "Can't get data !");
throw new Exception("Can't get data !");
}
} catch (Exception e) {
e.printStackTrace();
flightPlans = new ArrayList<>();
flightPlans.add(new FlightPlan(5, "Test5", 3.551, 50.52, 3.55122, 50.52625));
}
data.setValue(flightPlans);
Log.d(TAG, data.getValue().toString());
return data;
}
现在它在执行行上崩溃,因为我在主线程中启动了它。 所以我必须做一个异步任务,但是在哪里?
其他选项:首先像执行异步任务一样,将setter放置到模型视图对象中,当有响应时,我将其称为setter。这样做很好吗?
感谢您给我的请求!这很有帮助。
编辑:为什么在Google文档中有此代码:
public class UserRepository {
private Webservice webservice;
// ...
public LiveData<User> getUser(int userId) {
// This isn't an optimal implementation. We'll fix it later.
final MutableLiveData<User> data = new MutableLiveData<>();
webservice.getUser(userId).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
data.setValue(response.body());
}
// Error case is left out for brevity.
});
return data;
}
}
这意味着可以这样做吗?
解决方案!
编辑:
How to connect ViewModel with Repository so that data is propagated to the View (MVVM, Livedata)
这对我有很大帮助!
我找到了解决方案!我很愚蠢:我在gradle文件中插入了旧的依赖项!