UI is not updating while viewModel is updated in android kotlin - android

I am following the MVVM pattern Activity-->ViewModel ---> Repository . Repository is calling api and updated the LiveData. The value is of LiveData is also updated in ViewModel but its not reflecting on Activity. Please guide me where i am missing, Code is given below
Activity code:
class LoginWithEmailActivity : AppCompatActivity() {
private var loginViewModel: LoginViewModel? = null
private var binding: ActivityLoginWithEmailBinding? = null
private var btnLogin : Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loginViewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
binding = DataBindingUtil.setContentView(this#LoginWithEmailActivity, R.layout.activity_login_with_email)
binding!!.setLifecycleOwner(this)
binding!!.setLoginViewModel(loginViewModel)
btnLogin = findViewById(R.id.btn_login)
loginViewModel!!.servicesLiveData!!.observe(this, Observer<LoginDataModel?> { serviceSetterGetter ->
val msg = serviceSetterGetter.success
Toast.makeText(this#LoginWithEmailActivity, ""+msg, Toast.LENGTH_SHORT).show()
Log.v("///LOGIN SUCCESS////",""+msg);
})
btnLogin!!.setOnClickListener {
loginViewModel!!.getUser()
}
}
ViewModel.kt
class LoginViewModel : ViewModel() {
var servicesLiveData: MutableLiveData<LoginDataModel>? = MutableLiveData()
fun getUser() {
servicesLiveData = MainActivityRepository.getServicesApiCall()
}
}
Repository.kt
object MainActivityRepository {
val serviceSetterGetter = MutableLiveData<LoginDataModel>()
fun getServicesApiCall(): MutableLiveData<LoginDataModel> {
val params = JsonObject()
params.addProperty("email", "xyz#gmail.com")
val call: Call<LoginDataModel> = ApiClient.getClient.getPhotos(params)
call.enqueue(object : Callback<LoginDataModel> {
#RequiresApi(Build.VERSION_CODES.N)
override fun onResponse(call: Call<LoginDataModel>?, response: Response<LoginDataModel>?) {
if (response != null) {
val data = response.body()
serviceSetterGetter?.postValue(data);
}
}
override fun onFailure(call: Call<LoginDataModel>?, t: Throwable?) {
}
})
return serviceSetterGetter
}
}

You subscribe to the LiveData in onCreate
loginViewModel!!.servicesLiveData!!.observe(this, Observer<LoginDataModel?> { serviceSetterGetter ->
val msg = serviceSetterGetter.success
Toast.makeText(this#LoginWithEmailActivity, ""+msg, Toast.LENGTH_SHORT).show()
Log.v("///LOGIN SUCCESS////",""+msg);
})
but then getUser creates a new reference
fun getUser() {
servicesLiveData = MainActivityRepository.getServicesApiCall()
}
The one you are subscribed to is not the same as the getUser liveData.
If you want to keep what you have mostly the same you need to use MediatorLiveData
Or just do
getUser().observe(this, Observer<LoginDataModel?> { serviceSetterGetter ->
val msg = serviceSetterGetter.success
Toast.makeText(this#LoginWithEmailActivity, ""+msg, Toast.LENGTH_SHORT).show()
Log.v("///LOGIN SUCCESS////",""+msg);
})
fun getUser(): LiveData<LoginDataModel> {
return MainActivityRepository.getServicesApiCall()
}

Related

ProgressBar not showing and observing in MVVM pattern

I am trying to observe a progressBar and everything seems ok to me but its not working..
when it gets to the viewmodel its getting null value..
This is the repository:
val isLoadingProgressBarMutableLiveData = MutableLiveData<Boolean>()
fun getEmployeeListFromAPI(): MutableLiveData<List<Employee>> {
isLoadingProgressBarMutableLiveData.value = true
val apiRequest: APICallRequest = APIRequest.retrofitCallGetList
apiRequest.callEmployeeList().enqueue(object : Callback<EmployeesListResult?> {
override fun onResponse(
call: Call<EmployeesListResult?>,
response: Response<EmployeesListResult?>
) {
Log.e("onResponse1", "${isLoadingProgressBarMutableLiveData.value}")
if (response.isSuccessful) {
isLoadingProgressBarMutableLiveData.value = false
mutableListLiveData.value = response.body()?.getEmployeesListResult
Log.e("onResponse2", "${isLoadingProgressBarMutableLiveData.value}")
Log.e("onResponse", "Success!")
Log.e("Response:", "${response.body()}")
}
}
override fun onFailure(call: Call<EmployeesListResult?>, t: Throwable) {
Log.e("onFailure", "Failed getting list: ${t.message}")
isLoadingProgressBarMutableLiveData.value = false
}
})
return mutableListLiveData
}
fun getLoadingState() : MutableLiveData<Boolean>{
return isLoadingProgressBarMutableLiveData
}
"onResponse1" = true
"onResponse2" = false
but when I move it to the ViewModel I get null ...
This is the ViewModel:
class MainViewModel : ViewModel() {
fun getEmployeeListFromRepo() : LiveData<List<Employee>>{
return MainRepository().getEmployeeListFromAPI()
}
fun showProgressBar(): LiveData<Boolean> {
Log.e("Progress","ddd ${MainRepository().getLoadingState().value}")
return MainRepository().getLoadingState()
}
}
"ProgressBar" = is null
And in the activity:
mainViewModel.showProgressBar().observe(this, object : Observer<Boolean?> {
override fun onChanged(isLoading: Boolean?) {
Log.e("isLoadingProgressBar:", "Loading is...: $isLoading")
if (isLoading == true){
progressBar.visibility = View.VISIBLE
}else{
progressBar.visibility = View.GONE
}
}
})
Buddy - every time you do MainRepository() you're creating a new repository and accessing that. You should have one repository you're working with.
class MainViewModel : ViewModel() {
private val repository = MainRespository() // ONE repo
fun getEmployeeListFromRepo() : LiveData<List<Employee>>{
return repository.getEmployeeListFromAPI() // Get the live data to the ONE repo instead of creating a new one
}
fun showProgressBar(): LiveData<Boolean> {
// Print and return the value from the ONE respository instead of creating
// TWO new ones in this method
Log.e("Progress","ddd ${respository.getLoadingState().value}")
return respository.getLoadingState()
}
}

Observing MediatorLiveData doesn't yeild any result (attached observer)

Basically, I am fetching the products list from this API using Retrofit into a MediatorLiveData inside ProductsRepository class. But, the problem is, when I try to observe the LiveData I get null.
Here is my code snippet:
ProductsRepository:
#MainScope
class ProductsRepository #Inject constructor(private val productsApi: ProductsApi) {
private val products: MediatorLiveData<ProductsResource<List<ProductsModel>>> =
MediatorLiveData()
fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>> {
products.value = ProductsResource.loading(null)
val source: LiveData<ProductsResource<List<ProductsModel>>> =
LiveDataReactiveStreams.fromPublisher {
productsApi.getProducts()
.onErrorReturn {
val p = ProductsModel()
p.setId(-1)
val products = ArrayList<ProductsModel>()
products.add(p)
products
}.map {
if (it[0].getId() == -1) {
ProductsResource.error("Something went wrong", null)
}
ProductsResource.success(it)
}.observeOn(Schedulers.io())
}
products.addSource(source){
products.value = it
products.removeSource(source)
}
return products
}
}
MainViewModel
class MainViewModel #Inject constructor(private val repository: ProductsRepository): ViewModel() {
fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>>{
return repository.getProducts()
}
}
MainActivity:
class MainActivity : DaggerAppCompatActivity() {
lateinit var binding: ActivityMainBinding
#Inject
lateinit var viewModelProviderFactory: ViewModelProviderFactory
lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initViewModel()
subscribeToObservers()
}
private fun subscribeToObservers(){
mainViewModel.getProducts()
.observe(this){
Log.d("", "subscribeToObservers: "+ it.data?.size)
}
}
private fun initViewModel() {
mainViewModel = ViewModelProvider(this, viewModelProviderFactory).get(MainViewModel::class.java)
}
}
If I call hasActiveObservers(), it returns false although I am observing it from the MainActivity.
Now, let's say if I replace the MediatorLiveData with MutableLiveData and refactor my ProductsRepository like below, I get my expected output.
fun getProducts(): LiveData<ProductsResource<List<ProductsModel>>> {
val products: MutableLiveData<ProductsResource<List<ProductsModel>>> = MutableLiveData()
products.value = ProductsResource.loading(null)
productsApi.getProducts()
.onErrorReturn {
//Log.d("MyError", it.message.toString())
val p = ProductsModel()
p.setId(-1)
val product = ArrayList<ProductsModel>()
product.add(p)
product
}.map { product ->
if (product.isNotEmpty()) {
if (product[0].getId() == -1) {
// Log.d("Map", "Error: ${product}")
ProductsResource.error(
"Something went Wrong",
null
)
}
}
ProductsResource.success(product)
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
products.value = it
}
return products
}
I don't know If I am successful in explaining my problem. Please, let me know If I need to provide more details or code snippets.
Thanks in advance

NetworkOnMainThreadException when using rxandroid and mvvm design pattern

I have an issue with my code which is throwing NetworkOnMainThreadException. I am trying to connect to an Android app to Odoo using Android XML-RPC library.
Here is what I am doing.
class OdooServiceImpl : OdooService {
/* This is the only function doing network operation*/
override fun userAuthenticate(
host: String,
login: String,
password: String,
database: String
): Single<Int> {
val client = XMLRPCClient("$host/xmlrpc/2/common")
val result =
client.call("login", database, login, password)
return Single.just(result as Int)
}}
This class is called from a repository class.
The repository if called by the viewmodel class using rxandroid
class OdooViewModel(private val mainRepository: OdooRepository, private val context: Context) :
ViewModel() {
val host = "https://myodoo-domain.com"
private val user = MutableLiveData<OdooResource<Int>>()
private val compositeDisposable = CompositeDisposable()
init {
authUser()
}
private fun authUser(){
user.postValue(OdooResource.authConnecting(null))
compositeDisposable.add(
mainRepository.userAuthenticate(host,"mylogin","mypassword","mdb")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (it != null) {
user.postValue(OdooResource.authSuccess(it))
} else {
user.postValue(
OdooResource.authError(
null,
msg = "Something went wring while authenticating to $host"
)
)
}
}, {
server.postValue(
OdooResource.conError(
null,
msg = "Something went wring while authenticating to $host"
)
)
})
)
}
override fun onCleared() {
super.onCleared()
compositeDisposable.dispose()
}
fun getUser(): LiveData<OdooResource<Int>> {
return user
}
}
I have called this class from my activity as follow
class OdooActivity : AppCompatActivity() {
private lateinit var odooViewModel: OdooViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_odoo)
setupViewModel()
setupObserver()
}
private fun setupObserver() {
odooViewModel.getUser().observe(this, Observer {
Log.i("TAGGG", "Tests")
when (it.status) {
OdooStatus.AUTHENTICATION_SUCCESS -> {
progressBar.visibility = View.GONE
it.data?.let { server -> textView.setText(server.toString()) }
textView.visibility = View.VISIBLE
}
OdooStatus.AUTHENTICATION -> {
progressBar.visibility = View.VISIBLE
textView.visibility = View.GONE
}
OdooStatus.AUTHENTICATION_ERROR -> {
//Handle Error
progressBar.visibility = View.GONE
Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
}
else -> {
}
}
})
}
private fun setupViewModel() {
val viewModelFactory = OdooViewModelFactory(OdooApiHelper(OdooServiceImpl()), this)
odooViewModel = ViewModelProviders.of(this, viewModelFactory).get(OdooViewModel::class.java)
}
}
When I run the app this is a the line which is throwing the error
odooViewModel = ViewModelProviders.of(this, viewModelFactory).get(OdooViewModel::class.java)
What am I missing here??
The culprit is here:
val result = client.call("login", database, login, password)
return Single.just(result as Int)
The call to generate the result is executed, when setting up the Rx chain, which happens on the main thread. You have to make sure that the network-call is done when actually subscribing (on io()). One solution could be to return a Single.fromCallable:
return Single.fromCallable { client.call("login", database, login, password) as Int }

Retrofit call using abstraction with kotlin is not calling onChange

I want to abstract the retrofit call, so I don't need to write the same boiler plate code when I need a request.
The abstraction
open class NetworkCall<T> {
lateinit var call: Call<T>
var result: MutableLiveData<Resource<T>> = MutableLiveData()
fun makeCall(call: Call<T>) {
this.call = call
val callBackKt = CallBackKt<T>()
callBackKt.result.value = Resource.loading(null)
this.call.enqueue(callBackKt)
result = callBackKt.result
}
class CallBackKt<T> : Callback<T> {
var result: MutableLiveData<Resource<T>> = MutableLiveData()
override fun onFailure(call: Call<T>, t: Throwable) {
result.value = Resource.error()//APIError()
t.printStackTrace()
}
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
result.value = Resource.success(response.body())
}
else {
result.value = Resource.error()
}
}
}
}
Repository
class DetailsRepository(val application: Application) {
private val myListDao =
AppDatabase.getDatabase(application)?.MyListDao()
var movie: MutableLiveData<Resource<DetailsDTO>> = MutableLiveData()
fun getDetails(id: Int) {
val networkCall = NetworkCall<DetailsDTO>()
networkCall.makeCall(Apifactory.tmdbApi.getDetails(id))
movie = networkCall.result
}
}
ViewModel
class DetailsViewModel(application: Application) : AndroidViewModel(application) {
private val repository: DetailsRepository = DetailsRepository(application)
internal var movie: LiveData<Resource<DetailsDTO>> = repository.movie
fun insert(myListItem: MyListItem) {
repository.insert(myListItem)
}
fun fetchDetails(id: Int) {
repository.getDetails(id)
}
}
Activity
viewModel.movie.observe(this, Observer {
it?.apply {
detail_title.text = data?.title
}
})
Log with in every method says it's being called in right order and that the request is working fine. Althoght onChange is not being called.
fetchDetails called
getDetails called
makeCall called
onResponse successful, result.value.data = DetailsDTO(adult=false, backdrop_path=/y8lEIjYZCi2VFP4ixtHSn2klpth.jpg, ...
...
What would be done wrong?

PostValue didn't update my Observer in MVVM

I have an activity to perform rest API everytime it opened and i use MVVM pattern for this project. But with this snippet code i failed to get updated everytime i open activity. So i debug all my parameters in every line, they all fine the suspect problem might when apiService.readNewsAsync(param1,param2) execute, my postValue did not update my resulRead parameter. There were no crash here, but i got result which not updated from result (postValue). Can someone explain to me why this happened?
Here what activity looks like
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivityReadBinding>(this,
R.layout.activity_read).apply {
this.viewModel = readViewModel
this.lifecycleOwner = this#ReadActivity
}
readViewModel.observerRead.observe(this, Observer {
val sukses = it.isSuccess
when{
sukses -> {
val data = it.data as Read
val article = data.article
//Log.d("-->", "${article.toString()}")
}
else -> {
toast("ada error ${it.msg}")
Timber.d("ERROR : ${it.msg}")
}
}
})
readViewModel.getReadNews()
}
Viewmodel
var observerRead = MutableLiveData<AppResponse>()
init {
observerRead = readRepository.observerReadNews()
}
fun getReadNews() {
// kanal and guid i fetch from intent and these value are valid
loadingVisibility = View.VISIBLE
val ok = readRepository.getReadNews(kanal!!, guid!!)
if(ok){
loadingVisibility = View.GONE
}
}
REPOSITORY
class ReadRepositoryImpl private constructor(private val newsdataDao: NewsdataDao) : ReadRepository{
override fun observerReadNews(): MutableLiveData<AppResponse> {
return newsdataDao.resultRead
}
override fun getReadNews(channel: String, guid: Int) = newsdataDao.readNews(channel, guid)
companion object{
#Volatile private var instance: ReadRepositoryImpl? = null
fun getInstance(newsdataDao: NewsdataDao) = instance ?: synchronized(this){
instance ?: ReadRepositoryImpl(newsdataDao).also {
instance = it
}
}
}
}
MODEL / DATA SOURCE
class NewsdataDao {
private val apiService = ApiClient.getClient().create(ApiService::class.java)
var resultRead = MutableLiveData<AppResponse>()
fun readNews(channel: String, guid: Int): Boolean{
GlobalScope.launch {
val response = apiService.readNewsAsync(Constants.API_TOKEN, channel, guid.toString()).await()
when{
response.isSuccessful -> {
val res = response.body()
val appRes = AppResponse(true, "ok", res!!)
resultRead.postValue(appRes)
}
else -> {
val appRes = AppResponse(false, "Error: ${response.message()}", null)
resultRead.postValue(appRes)
}
}
}
return true
}
}
Perhaps this activity is not getting stopped.
Check this out:
When you call readViewModel.getReadNews() in onCreate() your activity is created once, only if onStop is called will it be created again.

Categories

Resources