gpt4 book ai didi

android - 我应该在哪里将改造电话放在m​​vvm中并处理其响应

转载 作者:行者123 更新时间:2023-12-03 11:01:57 28 4
gpt4 key购买 nike

我正在尝试研究MVVM模式,不知道在哪里放置改造电话
在MVVM模式中以及如何处理其响应

这是我的loginviewmodel类

public class LoginViewModel extends ViewModel {
public MutableLiveData<String> email = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
public MutableLiveData<String> token = new MutableLiveData<>();
private MutableLiveData<Login> userMutableLiveData;

public MutableLiveData<Login> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData;
}

public void onClick(View view) {
Login loginUser = new Login(email.getValue(), password.getValue());
userMutableLiveData.setValue(loginUser);
loginAccount(loginUser);
}

private void loginAccount(final Login login) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

Api api = retrofit.create(Api.class);
Call<Token> call = api.login(new Login(login.getEmail(), login.getPassword()));

call.enqueue(new Callback<Token>() {
@Override
public void onResponse(Call<Token> call, Response<Token> response) {
//finally we are setting the list to our MutableLiveData
userMutableLiveData.setValue(new Login(login.getEmail(), login.getPassword(),"Login Successful"));
}

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

这是我在mainactivity中的oncreate

loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
binding.setLifecycleOwner(this);
binding.setLoginViewModel(loginViewModel);

loginViewModel.getUser().observe(this, new Observer<Login>() {
@Override
public void onChanged(@Nullable Login loginUser) {
if (TextUtils.isEmpty(Objects.requireNonNull(loginUser).getEmail())) {
binding.txtEmailAddress.setError("Enter an E-Mail Address");
binding.txtEmailAddress.requestFocus();
} else if (!loginUser.isEmailValid()) {
binding.txtEmailAddress.setError("Enter a Valid E-mail Address");
binding.txtEmailAddress.requestFocus();
} else if (TextUtils.isEmpty(Objects.requireNonNull(loginUser).getPassword())) {
binding.txtPassword.setError("Enter a Password");
binding.txtPassword.requestFocus();
} else if (!loginUser.isPasswordLengthGreaterThan5()) {
binding.txtPassword.setError("Enter at least 6 Digit password");
binding.txtPassword.requestFocus();
} else if (loginUser.getToken().equals("")) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
} else {
binding.tvToken.setText(loginUser.getToken());
}
}
});

我的activity_main.xml中也有一个textview,我希望在收到对API调用的响应(无论成功还是失败)之后,将响应发布到textview中。

我想知道这是正确的还是更好的方法?

谢谢!

最佳答案

View 模型应该处理您的应用程序的业务逻辑。最好将API调用放在Repository类中,请参见以下示例:

首先,为您的整个应用程序创建一个API层

object RestApiHelper {
private lateinit var retrofit: Retrofit
private const val CONNECTION_TIME_OUT: Long = 60

fun getService(): NetworkService {
retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getClient())
.build()
return retrofit.create(NetworkService::class.java)
}
}

然后是用于调用API的存储库类
object LoginRepo {
//Create Retrofit service to hit apis
private val webService = RestApiHelper.getService()

// Create function here to login
fun login(
successHandler: (Token) -> Unit,
errorHandler: (ApiError) -> Unit,
connectionError: (Throwable?) -> Unit,
request: Login
) {
webService.login(request).enqueue(object : Callback< Token > {
override fun onResponse(call: Call< Token >?, response: Response< Token >?) {
response?.body()?.let {
// success response
}
}

override fun onFailure(call: Call< Token >?, t: Throwable?) {

}

})
}
}

从ViewModel类中,只需调用此仓库
class LoginViewModel : BaseViewModel() {
var mApiSuccess = MutableLiveData<Token>()

fun serverLogin(request: Login) {
LoginRepo.login({
mApiSuccess.value = it // Lambda function
}, {
mApiError.value = it // Lambda function
}, {
mConnectionFailure.value = it // Lambda function
}, request)

}
}

还有BaseViewModel
open class BaseViewModel : ViewModel() {
var mApiError = MutableLiveData<ApiError>()
var mConnectionFailure = MutableLiveData<Throwable>()
}

这样,您就可以将关注点分开,ViewModel将从存储库中查询数据,现在您的存储库将提供您喜欢的源(网络/缓存/文件系统/数据库)中的数据,而您的模型永远都不知道数据源。
现在 :
  • View :负责UI
  • 模型:业务逻辑
  • repo :数据提供者
  • 关于android - 我应该在哪里将改造电话放在m​​vvm中并处理其响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57412194/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com