Android - MVVM с компонентом LiveData и вызовом Retrofit в репозитории - PullRequest
0 голосов
/ 18 октября 2018

Я хотел бы использовать следующие компоненты для представления аутентификации (Вход в систему):

  • MVVM
  • LiveData
  • Модификация
  • Репозиторий

Я не знаю, как получить асинхронный вызов Retrofit в классе репозитория для текущей модели ViewModel.

View -> ViewModel -> Репозиторий с LiveData.

У кого-нибудь была бы идея или пример, чтобы это заархивировать?

Ответы [ 2 ]

0 голосов
/ 21 января 2019

Самый простой способ создать свой проект в MVVM с использованием LiveData и Retrofit - это использовать LiveData в вашем классе ViewModel и Retrofit в вашем репозитории.

С точки зрения непрофессионала, вы получаете данные из своего репозитория в своем классе ViewModel и в своем классе ViewModel, передаете эти данные в MutableLiveData , и затем эти MutableLiveData можно наблюдать в вашем представлении:преобразование его в LiveData.

MainActivity.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) {
            return response;
        }

        @Override
        public void onFailure(Call<ModelForPostRequest> call, Throwable t) {
        }
    });
}}
0 голосов
/ 18 октября 2018

Вы можете сделать, как показано ниже:

YourActivity.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
    })
}
}

MyViewModel.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()
        }

    })
}
}

Попробуйте выполнить настройку следующим образом.

Надеюсь, это поможет!

...