mvp+retrofit+rxjava

来源:http://www.cnblogs.com/LiuZhen/archive/2016/07/30/5720649.html
-Advertisement-
Play Games

引用 "retrofit" : "com.squareup.retrofit2:retrofit:2.0.1", "retrofit-adapter" : "com.squareup.retrofit2:adapter-rxjava:2.0.1", "retrofit-converter" : "c ...


引用

"retrofit"              : "com.squareup.retrofit2:retrofit:2.0.1",
                    "retrofit-adapter"      : "com.squareup.retrofit2:adapter-rxjava:2.0.1",
                    "retrofit-converter"    : "com.squareup.retrofit2:converter-gson:2.0.1",

                    "gson"                  : "com.google.code.gson:gson:2.6.2",

                    "rxjava"                : "io.reactivex:rxjava:1.1.2",
                    "rxandroid"             : "io.reactivex:rxandroid:1.1.0",

                    "okhttp"                : "com.squareup.okhttp3:okhttp:3.2.0",
                    "okhttp-urlconnection"  : "com.squareup.okhttp3:okhttp-urlconnection:3.2.0",
                    "okhttp-logging"        : "com.squareup.okhttp3:logging-interceptor:3.2.0",
                    "okhttp-cookie"         : "com.github.franmontiel:PersistentCookieJar:v0.9.3",
View Code

Retrofit

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**用於輔助初始化retrofit**/
public class RxService {

    private static final long DEFAULT_TIMEOUT = 20L;

    final static Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .serializeNulls()// 調用serializeNulls方法,改變gson對象的預設行為,null值將被輸出
            .create();

    //addInterceptor:設置應用攔截器,可用於設置公共參數,頭信息,日誌攔截等
    //addNetworkInterceptor:網路攔截器,可以用於重試或重寫,對應與1.9中的setRequestInterceptor。
    //setLevel NONE(不記錄) BASIC(請求/響應行)  HEADER(請求/響應行 + 頭)  BODY(請求/響應行 + 頭 + 體)
    //cookieJar:保持在同一個會話裡面
    //TimeUnit.SECONDS秒做單位
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.HEADERS))
            .addInterceptor(new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BODY))
            .cookieJar(App.getInstance().getCookieJar())
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .build();

    private static Retrofit retrofit = null;

    private RxService() {}

//    private final static RxService rxService = new RxService();

    public static <T> T createApi(Class<T> clazz,String url) {
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        return retrofit.create(clazz);
    }

    public static <T> T createApi(Class<T> clazz) {
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_DEFAULT)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        return retrofit.create(clazz);
    }

}
View Code
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;

/**
 * Created by JDD on 2016/4/8.
 */
public interface ILoginService {

    @FormUrlEncoded
    @POST(LoginSingleService.URL)
    Observable<UsersEntity> login(@Field("token") String token, @Field("userName") String userName, @Field("userPassword") String userPassword);
}
View Code
/**創建並配置retrofit service**/
public class LoginSingleService {

    public static final String URL = "login.do";
    protected static final Object monitor = new Object();
    static ILoginService sJokeSingleton = null;
//    public static final int meizhiSize = 10;
//    public static final int gankSize = 5;

    //測試service
    public static ILoginService getLoginSingleton() {
        synchronized (monitor) {
            if (sJokeSingleton == null) {
                sJokeSingleton = RxService.createApi(ILoginService.class);
            }
            return sJokeSingleton;
        }
    }



}
View Code
Presenter
import android.util.Log;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginPresenter implements ILoginPresenter {

    public Subscription login(final String username,final String pwd, final CallBack callBack) {
        if (username == null || pwd == null || username.equals("") || pwd.equals("")){
            callBack.Error(STATUS.NULL_ERROR);
            return null;
        }
        //觀察者Subscription
        Subscription s = LoginSingleService.getLoginSingleton()//事件源,被觀察者Observable
                .login("21341234",username,pwd)
                .subscribeOn(Schedulers.io())//指定觀察者運行的線程
                .map(entity -> entity.getData())
                .observeOn(AndroidSchedulers.mainThread())//指定訂閱者運行的線程
                .subscribe(new Observer<UserEntity>() {//訂閱subscriber
                    @Override
                    public void onCompleted() {
                        Log.e("onNext","onCompleted");
                        callBack.End();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("onNext","onError "+e.getMessage());
                        callBack.Error(STATUS.ERROR);
                    }

                    @Override
                    public void onNext(UserEntity entity) {
                        STATUS status;
                        if (entity != null) {
                            status = STATUS.SUCCESS;
                            Log.e("onNext","hello "+entity.getName());
                            App.getInstance().setUserEntity(entity);
                            App.getInstance().setPerson(entity,pwd);
                        }
                        else
                            status = STATUS.ERROR;

                        callBack.Success(status);
                    }
                });
        return s;
    }

}
View Code

Main

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by LiuZhen on 2016/5/11.
 */
public abstract class BaseActivity extends AppCompatActivity {

    private final static String TAG = "BaseActivity";
    private CompositeSubscription mCompositeSubscription;
    protected Context context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        this.context = BaseActivity.this;
    }

    public CompositeSubscription getCompositeSubscription() {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }

        return this.mCompositeSubscription;
    }
    /**使CompositeSubscription持有訂閱**/
    public void addSubscription(Subscription s) {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }

        this.mCompositeSubscription.add(s);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.mCompositeSubscription != null) {
            this.mCompositeSubscription.unsubscribe();//取消所有的訂閱
        }
    }

    protected abstract int getLayoutId();

}
View Code
import android.os.Bundle;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends BaseActivity {

    private TextView username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);

        username = (TextView) findViewById(R.id.username);
        username.setText(App.getInstance().getPerson().getName()+" hello");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent() {
        Toasts.showShort("刷新UI",context);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
View Code

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ajax 非同步請求成功後需要新開視窗打開 url,使用的是 window.open() 方法,但是很可惜被瀏覽器給攔截了,怎麼解決這個問題呢 ajax 非同步請求成功後需要新開視窗打開 url,使用的是 window.open() 方法,但是很可惜被瀏覽器給攔截了,怎麼解決這個問題呢 問題: 前面開發 ...
  • DOM有三種節點:元素節點、屬性節點、文本節點。 一、用nodeType可以檢測節點的類型 這樣方便在js中對各個節點進行操作。 元素節點:html中的標簽。 屬性節點:html便簽中的屬性值。 文本節點:元素節點之間的文本。 二、用body的childNodes來測試 來看body的childNo ...
  • 第63條建議使用工具函數downloadAllAsync接收一個URL數組並下載所有文件,結果返回一個存儲了文件內容的數組,每個URL對應一個字元串。downloadAllAsync並不只有清理嵌套回調函數的好處,其主要好處是並行下載文件。我們可以在同一個事件迴圈中一次啟動所有文件的下載,而不用等待... ...
  • 繼承的定義 ECMAScript 實現繼承可以從父類入手,所有開發者定義的類都可作為父類,出於安全考慮,本地類和宿主類不能作為父類,因為容易收到惡意攻擊 創建只是用於給子類提供通用函數的父類被看作抽象類 子類可以繼承父類的所有屬性和方法,子類可以擴展父類中沒有的屬性和方法,還可以覆蓋父類中的屬性和方 ...
  • 首先,你需要已經配置過你的rout,比如: 其中註意第二個地址信息中的params屬性,這個就是你要接受參數的對象,以key :value的形式定義 而在跳轉頁面時,兩個方法都可以傳參,一種是直接寫在html中 此時傳參跟在頁面地址的後面 第二種就是寫在controller中 同樣參數寫在地址後面, ...
  • 事件流講解來襲,嘎嘎嘎嘎嘎 1.事件流:描述的是在頁面中接受事件的順序。 2.事件冒泡:由最具體的元素接收,然後逐級向上傳播至最不具體的元素的節點(文檔)。 3.事件捕獲:最不具體的節點先接收事件,而最具體的節點應該是最後接收事件。 事件處理: 1.HTML事件處理:直接添加到HTML結構中(例:之 ...
  • bind()函數是在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運行。這就需要我們自己實現bind()函數了 簡單實現bind()方法: 考慮到函數柯里化的情況,我們可以構建一個更加健壯的bind(): 這次的bind()方法可以綁定對象,也支持在綁定的時候傳參。 繼續,Javasc ...
  • 一、自定義Dialog繼承Dialog 二、為Dialog設置樣式 在style中建立新樣式繼承 設置樣式去掉邊框 去掉標題 設置視窗透明 設置點擊對話框外邊可以消失等 設置動畫 進入動畫 退出 三、在構造方法中設置樣式 四、設置佈局 佈局文件就是2個TextView 五、重寫show方法,設置寬度 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...