简单的MVP+Retrofit+RxJava请求网络数据(一)

  • 废话不多说,直接看代码就行了。
public interface service {
    @GET("cook/query?key=03c27b647366189ba474393177559ea7&menu=秘制红烧肉&rn=20&pn=0")
    Observable postfix( );
}

View层:

public interface IView {
}
public class Persenter<T extends IView>{
    private T homeView;

    public void attachView(T homeActivity) {
        this.homeView=homeActivity;
    }

    public T getHomeView() {
        return homeView;
    }
}
public interface InLoginView<T> extends IView{
        void callbackData(T t);
        void callbackErrer(String errcode);
        }

Model层:

public class HttpDataModel {

    public static void getLoginHttpData(String url, Observer observer){

        Retrofit build = new Retrofit.Builder()
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        service inPostfix = build.create(service.class);
        inPostfix.postfix()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}

Presenter层:

public class LogInPersenter extends Persenter {
    private String url="http://apis.juhe.cn/";
    public void getLoginNwtWorkData() {
        HttpDataModel.getLoginHttpData(url, new Observer() {
            @Override
            public void onSubscribe( Disposable d) {
            }

            @Override
            public void onNext( bean o) {
                Log.e("zzzzzzzzzz :   " , o.toString());
            }

            @Override
            public void onError( Throwable e) {
                Log.e("zzzzzzzzzz--------- : " , e.toString());
            }

            @Override
            public void onComplete() {

            }
        });

    }
}

View层:

public class MainActivity extends AppCompatActivity implements InLoginView<bean> {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LogInPersenter logInPersenter = new LogInPersenter();
        logInPersenter.attachView(MainActivity.this);
        logInPersenter.getLoginNwtWorkData();

    }

    @Override
    public void callbackData(bean bean) {
        Log.e("zzzzzz   :  ",bean.getResult().getData().get(0).getTitle());
    }

    @Override
    public void callbackErrer(String errcode) {

    }
}

Bean里里面一定要有tostring()方法。

你可能感兴趣的:(Android)