使用service / dao图层模式的Android项目“后端”的最佳架构

时间:2018-01-30 21:58:30

标签: java android rest design-patterns okhttp

我尝试使用Spring Boot(REST)作为后端和Android作为前端来启动项目。 问题出在android项目中,因为我想使用Service - Controller模式。

当我将用于管理其他类中的http请求/响应的代码(例如UserService)放在主线程之外时,这无法操纵UI。

我正在阅读“runonuithread”,但UI的元素不在Service类中......在这种情况下我该怎么办?将元素添加到类或管理UserService内的上下文?

这是针对异步调用的..但是当我不想进行同步调用时,这是必要的吗?

1 个答案:

答案 0 :(得分:1)

这是使用EventBus的最佳方案。

在活动中,您可以订阅活动,从服务中,您将发布活动。

<强>活动/ Fragment.java

// ======= EventBus Subscribers =======
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onEvent(ActionEvent event)
{
    // Maniupulate the UI directly
    titleTextView.setText(event.getTitle());
    messageTextView.setText(event.getMessage());
}

<强> ActionEvent.class

// A Simple Class with the required properties
public class ActionEvent{

    private final String   title;
    private final String   message;

    public ActionEvent(String title, String message) {
        this.title = title;
        this.message = message;
    }

    ...
    // Getters and any other required stuff 
    ...
}

<强> Service.java

// Appropriately compose and Post the event
ActionEvent event = new ActionEvent("Some Title", "Some Message");
EventBus.getDefault().post(event);