简体   繁体   English

android MVP-如何从模型调用网络层?

[英]android MVP - How should the network layer be called , from model?

In MVP android i believe the network layer (retrofit , volley etc) should NOT be apart of the model. 在MVP android中,我认为网络层(改造,凌空等)不应与模型分开。 But I need a firm example on how to construct the model then. 但是,我需要一个有关如何构建模型的明确示例。 Should the model be a singleton that the network layer simply creates when api call completes ? 模型应该是api调用完成时网络层简单创建的单例吗?

Lets take a look at a presenter i have for my one of my activities: 让我们看一下我参加我的一项活动的主持人:

    public class MainActivityPresenter implements IMainPresenterContract, Callback {

    IMainActivityViewContract view;//todo set up a weak reference to View to avoid leakage
    NewsService interactor;

    public MainActivityPresenter(IMainActivityViewContract view, NewsService interactor) {
        this.view = view;
        this.interactor = interactor;
    }


    public void loadResource() {
        interactor.loadResource();
    }


    public void onRequestComplete(final NewsEntities newsEntities) {

        view.dataSetUpdated(newsEntities.getResults());
    }

    @Override
    public void onResult(final NewsEntities newsEntities) {
        onRequestComplete(newsEntities);
    }

    public void goToDetailsActivity(Result result) {
        view.goToDetailsActivity(result);
    }
}

So my question is about the NewsService interactor parameter i am passing into the constructor. 所以我的问题是关于我要传递给构造函数的NewsService交互器参数。 I was assuming this should be model data and not a networking service. 我以为这应该是模型数据,而不是网络服务。 But what should it look like then ? 但是那会是什么样子呢? Currently mine looks like this: 目前我的看起来像这样:

    public class NewsService implements INewsServiceContract {

    private Gson gson;
    private Callback mCallback;


    public NewsService() {
        configureGson();
    }

    private static String readStream(InputStream in) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {

            String nextLine;
            while ((nextLine = reader.readLine()) != null) {
                sb.append(nextLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public void setCallBack(Callback cb) {
        mCallback = cb; // or we can set up event bus
    }

    private void configureGson() {


        GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation();
        gson = builder.create();
    }

    @Override
    public void loadResource() {
//Todo could use a loader instead help with the config change or a headless fragment
        new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... params) {
                String readStream = "";
                HttpURLConnection con = null;
                try {
                    URL url = new URL("https://api.myjson.com/bins/nl6jh");
                    con = (HttpURLConnection) url.openConnection();
                    readStream = readStream(con.getInputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                finally {
                    if(con!=null)
                    con.disconnect();
                }
                return readStream;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                NewsService.this.onRequestComplete(result);


            }
        }.execute();
    }

    private void onRequestComplete(String data) {

        data = data.replaceAll("\"multimedia\":\"\"", "\"multimedia\":[]");
        news.hotels.com.sample.Model.NewsEntities newsEntities = gson.fromJson(data, NewsEntities.class);
        mCallback.onResult(newsEntities);
    }
}

so as you can see the NewsService in this case is doing the network calls. 因此您可以看到在这种情况下NewsService正在进行网络调用。 I think i should not have passed this into the presenter. 我认为我不应该将此内容传递给演示者。 But how can the model be constructed then ? 但是,如何构建模型呢? who calls the NewsService ? 谁叫NewsService?

UPDATE: THIS QUESTION WAS a long time ago, everyone please use clean architecture approach, and let your presenter know nothing about the network layer. 更新:这个问题是很久以前的,每个人都请使用简洁的体系结构方法,并让您的演示者对网络层一无所知。

the network calls need to be in Model layer and should be triggered from the presenter. 网络调用必须在“模型”层中,并应由演示者触发。 but its the Model layer who decides where to et the data and its hidden from the Presenter layer. 但由Model层负责决定数据的发布位置,以及对Presenter层的隐藏。

I myself use an interactor class to do this that is in model layer and a presenter will use this interactor to get the data and the interactor will get the data from DB or Server regarding to the situation. 我本人使用一个交互器类来执行此操作,该类在模型层中,并且演示者将使用此交互器来获取数据,并且该交互器将从DB或Server获取有关情况的数据。

look at this sample project in my repo: 看看我的仓库中的这个示例项目:

https://gitlab.com/amirziarati/Echarge https://gitlab.com/amirziarati/Echarge

I used Dagger to do DI that may confuse you. 我使用Dagger进行DI可能会使您感到困惑。 just look at packaging and how i seperate concerns between layers. 只看包装,以及我如何将关注点分开。

UPDATE: I used presenter to sync data from server and DB which is WRONG. 更新:我使用演示者来同步服务器和错误的数据库中的数据。 the presenter should know nothing about this proccess. 演示者对此过程一无所知。 I didnt recognize this problem that time. 那个时候我没有意识到这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM