2017-09-13 70 views
0

在我的應用程序中有一種通過API獲取數據的方法。它在IntentService中執行。接收到的數據被寫入數據庫。我在rxjava的幫助下重寫了這個方法,但執行時間大大增加了。 這是我在IntentService代碼Android我的代碼rxjava緩慢工作

Call<List<DocLine>> DocLineResult = mApi.getDocLine(UserID, LastUserDate); 
Response<List<DocLine>> responseDocLine = DocLineResult.execute(); 
if (responseDocLine.isSuccessful()) { 
    List<DocLine> docLines = responseDocLine.body(); 
    if (docLines != null) { 
     for (DocLine item : docLines) { 
      mContents = new ContentValues(); 
      //filling mContents from item 
      dbBase.insertWithOnConflict(dbTabName, null, mContents, SQLiteDatabase.CONFLICT_REPLACE); 
     } 
     Log.d(AppGlobal.LOG_TAG, dbTabName + " => " + docLines.size()); 
    } 
} 
else { 
    if (responseDocHead.raw() != null && responseDocHead.raw().code() == 404) { 
     throw new Exception(getString(R.string.error_null_user)); 
    else 
     throw new Exception("Error"); 
    } 
} 

這裏是我的代碼rxjava

Observable oDocLine = apiService.getDocLine(userId, lastSyncDate) 
      .flatMap(Observable::from) 
      .flatMap(docLine -> Observable.create(subscriber -> {workDB.save(docLine, null); subscriber.onCompleted();}) 
      .subscribeOn(Schedulers.io())); 
+0

請不要混合使用pascalcase和camelcase進行變量命名。它使你的代碼無法閱讀 –

+0

謝謝你的批評 – user1854307

+0

它的建設性,嘗試遵循java命名約定 –

回答

0

你第二flatmap似乎起不到任何有用的目的除了增加一個副作用。

Observable oDocLine = apiService.getDocLine(userId, lastSyncDate) 
      .flatMap(Observable::from)    
      .subscribeOn(Schedulers.io()) 
      .observeOn(Schedulers.io()) 
      .subscribe(docLine -> workDB.save(docLine, null)); 

應該是希望更有效率。