簡體   English   中英

Android - 帶有 LiveData 組件的 MVVM 和 Repository 中的 Retrofit 調用

[英]Android - MVVM with LiveData component and a Retrofit call in Repository

我想將以下組件用於身份驗證視圖(登錄):

  • MVVM
  • 實時數據
  • 改造
  • 存儲庫

我不知道如何在 Repository 類中接收對當前 ViewModel 的異步 Retrofit 調用。

查看 -> ViewModel -> 帶有 LiveData 的存儲庫。

有人會有想法或例子來存檔嗎?

你可以這樣做:

你的活動.kt

class YourActivity : AppCompatActivity() {

private val myViewModel by lazy {
    return@lazy ViewModelProviders.of(this).get(MyViewModel::class.java) }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onViewReady(savedInstanceState)
    myViewModel.callApi() // You can do it anywhere, on button click etc..
    observeResponseData() // observe it once in onCreate(), it'll respect your activity lifecycle
}

private fun observeResponseData() {
    myViewModel.liveData.observe(this, Observer { data ->
        // here will be your response
    })
}
}

視圖模型.kt

class MyViewModel : ViewModel() {

val liveData = MutableLiveData<Your response type here>()
val myRepository = MyRepository()

fun callApi() {
    myRepository.callMyRetrofitApi(liveData)
}
}

MyRepository.kt

class MyRepository {
//Make your retrofit setup here

//This is the method that calls API using Retrofit
fun callMyRetrofitApi(liveData: MutableLiveData<Your response type here>) {
    // Your Api Call with response callback
    myRetrofitInstance.apiMethod.enqueue(object : Callback<Your response type here> {
        override fun onFailure(call: Call<Your response type here>, t: Throwable) {

        }

        override fun onResponse(call: Call<Your response type here>, response: Response<Your response type here>) {
            liveData.value = response.body()
        }

    })
}
}

嘗試像這樣進行設置。

希望能幫助到你 !

使用 LiveData 和 Retrofit 在 MVVM 中設計項目的最簡單方法是在 ViewModel 類中使用 LiveData,在存儲庫中使用 Retrofit。

通俗地說,您從 ViewModel 類和 ViewModel 類中的 Repository 獲取數據,將此數據傳遞給MutableLiveData ,然后可以通過將其轉換為 LiveData 在您的視圖中觀察此 MutableLiveData。

主活動.java

public class MainActivity extends AppCompatActivity {
        private MainViewModel mainViewModel;

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_instruction);
                mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
                mainViewModel.init();
                mainViewModel.getModelLiveData().observe(this, new Observer<MainResponse>() {
                @Override
                public void onChanged(@Nullable MainResponse mainResponse) {
                // Here you write logic which implements if the ViewModel data changes. 
             }}
         });
      }
    }

MainViewModel(您的 ViewModel)

public class MainViewModel extends ViewModel {
private MainRepo mainRepo;
private MutableLiveData<MainResponse> modelMutableLiveData = new MutableLiveData<>();
Disposable disposable;

public MainViewModel() {
}

public MainViewModel(MainRepo mainRepo) {
    this.mainRepo = mainRepo;
}

public void init() {
                    modelMutableLiveData.setValue(mainRepo.callRetrofit().body());
                }

public LiveData<MainResponse> getModelLiveData() {
    return modelMutableLiveData;
   }
}

MainRepository(您的存儲庫類)

    public class MainRepository{

            public void callRetrofit() {
                    apiInterface = 
        ApiClient.getClient(ApiClient.POST_STATUS_URL).create(ApiInterface.class);
        Call<ModelForPostRequest> call = apiInterface.likeItem(modelForPostRequest);
        call.enqueue(new Callback<ModelForPostRequest>() {
        @Override
        public void onResponse(Call<ModelForPostRequest> call, 
                Response<ModelForPostRequest> response) {
            //do something here
        }

        @Override
        public void onFailure(Call<ModelForPostRequest> call, Throwable t) {
        }
    });
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM