I have such issue:
Two fragments: A and B, which inject viewModel, but for some reason I have result of LiveData in both of my fragments.
How can I avoid triggering live data pushing me old value? How to reset liveData somehow or ignore old values? Thanks.
In both of them I am listening to LiveData changes like this:
#AndroidEntryPoint
class LoginFragment : MyBaseDebugFragment(R.layout.spinner_layout) {
#Inject
private val viewModel: AuthorizationViewModel by activityViewModels()
{
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
viewModel.loginActionLD.observe(viewLifecycleOwner) { loginStatus ->
//Do something regarding the value of login status.
}
viewModel.DoLogin()
}
#HiltViewModel
class AuthorizationViewModel #Inject constructor(
private val login: LoginUseCase,
private val logout: LogoutUseCase,
#Dispatcher.IO private val ioDispatcher: CoroutineDispatcher,
#Scope.Application private val externalScope: CoroutineScope,
) : ViewModel() {
private val _loginActionLD = MutableLiveData<LoginAction>()
val loginActionLD: LiveData<LoginAction> = _loginActionLD
fun DoLogin(from: AuthRequest) {
launchOnMyExternalScope {
_loginActionLD.postValue(login().toLoginAction(from))
}
}
private fun launchOnMyExternalScope(block: suspend CoroutineScope.() -> Unit) =
externalScope.launch(ioDispatcher, block = block)
}
}
#Module
#InstallIn(SingletonComponent::class)
object CoroutineScopeModule {
#Singleton
#Scope.Application
#Provides
fun provideApplicationScope(#Dispatcher.IO ioDispatcher: CoroutineDispatcher): CoroutineScope =
CoroutineScope(SupervisorJob() + ioDispatcher)
}
#Qualifier
#Retention(AnnotationRetention.BINARY)
annotation class Scope {
#Qualifier
#Retention(AnnotationRetention.BINARY)
annotation class Application
}
There is a handy class SingleLiveEvent that you can use instead of LiveData in your ViewModel class to send only new updates after subscription.
class SingleLiveEvent<T> : MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, Observer<T> { t ->
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
})
}
override fun setValue(t: T?) {
pending.set(true)
super.setValue(t)
}
fun call() {
postValue(null)
}
}
This LiveData extension only calls the observable if there's an explicit call to setValue() or call().
Here is what helped me to avoid LiveData to trigger twice it's handler. This code is tested carefully:
open class LiveEvent<T> : MediatorLiveData<T>() {
private val observers = ArraySet<OneTimeObserver<in T>>()
#MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
val wrapper = OneTimeObserver(observer)
observers.add(wrapper)
super.observe(owner, wrapper)
}
#MainThread
override fun observeForever(observer: Observer<in T>) {
val wrapper = OneTimeObserver(observer)
observers.add(wrapper)
super.observeForever(wrapper)
}
#MainThread
override fun removeObserver(observer: Observer<in T>) {
if ((observer is OneTimeObserver && observers.remove(observer)) || observers.removeIf { it.observer == observer }) {
super.removeObserver(observer)
}
}
#MainThread
override fun setValue(t: T?) {
observers.forEach { it.newValue() }
super.setValue(t)
}
private class OneTimeObserver<T>(val observer: Observer<T>) : Observer<T> {
private var handled = AtomicBoolean(true)
override fun onChanged(t: T?) {
if (handled.compareAndSet(false, true)) observer.onChanged(t)
}
fun newValue() {
handled.set(false)
}
}
}
And then instead of such code:
private val _loginAction = MutableLiveData<LoginAction>()
val loginActionLD: LiveData<LoginAction> = _loginAction
I have used this code:
private val _loginAction = LiveEvent<LoginAction>()
val loginActionLD: LiveData<LoginAction> = _loginAction
Related
When we have a liveData as below, we cannot _liveData.value++, as the value is nullable.
class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
private val _liveData: MutableLiveData<Int> =
savedStateHandle.getLiveData("SomeKey", 0)
val liveData: LiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
The article https://proandroiddev.com/improving-livedata-nullability-in-kotlin-45751a2bafb7 provide a solution, i.e.
#Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T>(value: T) : LiveData<T>(value) {
override fun getValue(): T = super.getValue() as T
public override fun setValue(value: T) = super.setValue(value)
public override fun postValue(value: T) = super.postValue(value)
}
But that didn't support savedState.
How can we get a non-nullable LiveData that also has savedstate?
I have a solution that duplicate the data and don't look that elegant
#Suppress("UNCHECKED_CAST")
class SafeMutableLiveData<T: Any>(private val mutableLiveData: MutableLiveData<T>) :
MutableLiveData<T>(mutableLiveData.value) {
override fun getValue(): T = mutableLiveData.value as T
override fun setValue(value: T) {
super.setValue(value)
mutableLiveData.value = value
}
override fun postValue(value: T) {
super.postValue(value)
mutableLiveData.postValue(value)
}
}
The usage is as below
class MainViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
private val _liveData: SafeMutableLiveData<Int> =
SafeMutableLiveData(savedStateHandle.getLiveData("Something", 0))
val liveData: LiveData<Int> = _liveData
fun triggerLiveData() {
_liveData.value++
}
}
I have a MainActivity form that I am opening CreatePassword Activity in that, I am saving password and finish CreatePasswordActivity with sending Intent back to MainActivity.
Like MainActivity -----> CreatePassword(Finish) ---Intent----> MainActivity
private fun observeIntentResult() {
generatePasswordViewModel.getIntentResult().observe(this#CreatePasswordActivity, androidx.lifecycle.Observer { intent ->
Toast.makeText(this, "Got Same Data", Toast.LENGTH_SHORT).show()
setResult(Activity.RESULT_OK, intent)
finish()
})
}
But Now when I open CreatePasswordActivity again from MainActivity, it's LiveData automatically sending previous data (intent) and CreatePasswordActivity is suddenly finished.
Do I have any mistake in implementing code? Anybody have idea how to resolve this?
Finally I have used below class, which helped me to resolve current issue, will see and update answer in future if I will be able to find any better solution.
open class VolatileLiveData<T> : MutableLiveData<T>() {
private val lastValueSeq = AtomicInteger(0)
private val wrappers = HashMap<Observer<in T>, Observer<T>>()
#MainThread
public override fun setValue(value: T) {
lastValueSeq.incrementAndGet()
super.setValue(value)
}
#MainThread
public override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
val observerWrapper = ObserverWrapper(lastValueSeq, observer)
wrappers[observer] = observerWrapper
super.observe(owner, observerWrapper)
}
#MainThread
public override fun observeForever(observer: Observer<in T>) {
val observerWrapper = ObserverWrapper(lastValueSeq, observer)
wrappers[observer] = observerWrapper
super.observeForever(observerWrapper)
}
#MainThread
public override fun removeObserver(observer: Observer<in T>) {
val observerWrapper = wrappers[observer]
observerWrapper?.let {
wrappers.remove(observerWrapper)
super.removeObserver(observerWrapper)
}
}
}
private class ObserverWrapper<T>(private var currentSeq: AtomicInteger, private val observer: Observer<in T>) : Observer<T> {
private val initialSeq = currentSeq.get()
private var _observer: Observer<in T> = Observer {
if (currentSeq.get() != initialSeq) {
// Optimization: this wrapper implementation is only needed in the beginning.
// Once a valid call is made (i.e. with a different concurrent sequence), we
// get rid of it any apply the real implementation as a direct callthrough.
_observer = observer
_observer.onChanged(it)
}
}
override fun onChanged(value: T) {
_observer.onChanged(value)
}
}
MainActivity
class MainActivity : AppCompatActivity() {
#Inject
lateinit var mainViewModelFactory: mainViewModelFactory
private lateinit var mainActivityBinding: ActivityMainBinding
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivityBinding = DataBindingUtil.setContentView(
this,
R.layout.activity_main
)
mainActivityBinding.rvmainRepos.adapter = mainAdapter
AndroidInjection.inject(this)
mainViewModel =
ViewModelProviders.of(
this#MainActivity,
mainViewModelFactory
)[mainViewModel::class.java]
mainActivityBinding.viewmodel = mainViewModel
mainActivityBinding.lifecycleOwner = this
mainViewModel.mainRepoReponse.observe(this, Observer<Response> {
repoList.clear()
it.success?.let { response ->
if (!response.isEmpty()) {
// mainViewModel.saveDataToDb(response)
// mainViewModel.createWorkerForClearingDb()
}
}
})
}
}
MainViewModelFactory
class MainViewModelFactory #Inject constructor(
val mainRepository: mainRepository
) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>) =
with(modelClass) {
when {
isAssignableFrom(mainViewModel::class.java) -> mainViewModel(
mainRepository = mainRepository
)
else -> throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
}
} as T
}
MainViewModel
class MainViewModel(
val mainRepository: mainRepository
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val mainRepoReponse = MutableLiveData<Response>()
val loadingProgress: MutableLiveData<Boolean> = MutableLiveData()
val _loadingProgress: LiveData<Boolean> = loadingProgress
val loadingFailed: MutableLiveData<Boolean> = MutableLiveData()
val _loadingFailed: LiveData<Boolean> = loadingFailed
var isConnected: Boolean = false
fun fetchmainRepos() {
if (isConnected) {
loadingProgress.value = true
compositeDisposable.add(
mainRepository.getmainRepos().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
run {
saveDataToDb(response)
)
}
},
{ error ->
processResponse(Response(AppConstants.Status.SUCCESS, null, error))
}
)
)
} else {
fetchFromLocal()
}
}
private fun saveDataToDb(response: List<mainRepo>) {
mainRepository.insertmainUsers(response)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(object : DisposableCompletableObserver() {
override fun onComplete() {
Log.d("Status", "Save Success")
}
override fun onError(e: Throwable) {
Log.d("Status", "error ${e.localizedMessage}")
}
})
}
}
MainRepository
interface MainRepository {
fun getmainRepos(): Single<List<mainRepo>>
fun getAllLocalRecords(): Single<List<mainRepo>>
fun insertmainUsers(repoList: List<mainRepo>): Completable
}
MainRepositoryImpl
class mainRepositoryImpl #Inject constructor(
val apiService: GitHubApi,
val mainDao: AppDao
) : MainRepository {
override fun getAllLocalRecords(): Single<List<mainRepo>> = mainDao.getAllRepos()
override fun insertmainUsers(repoList: List<mainRepo>) :Completable{
return mainDao.insertAllRepos(repoList)
}
override fun getmainRepos(): Single<List<mainRepo>> {
return apiService.getmainGits()
}
}
I'm quite confused with the implementation of MVVM with LiveData and Rxjava, in my MainViewModel I am calling the interface method and implementing it inside ViewModel, also on the response I'm saving the response to db. However, that is a private method, which won't be testable in unit testing in a proper way (because it's private). What is the best practice to call other methods on the completion of one method or i have to implement all the methods inside the implementation class which uses the interface.
Your ViewModel should not care how you are getting the data if you are trying to follow the clean architecture pattern. The logic for fetching the data from local or remote sources should be in the repository in the worst case where you can also save the response. In that case, since you have a contact for the methods, you can easily test them. Ideally, you could break it down even more - adding Usecases/Interactors.
I'm beginning with navigation components and I'm facing some problem with a livedata observer.
For example:
I have this livedata, who manage auth response from server.
viewModel.authenticate.observe(this, Observer {
manageAuthResponse(it)
})
Everything works fine, and I go to Fragment B.
But when I'm in Fragment B, and I try to go back to Fragment A (who contains that livedata), the Observer fires again with the previous result (SUCCESS).
How can I prevent this?
When I go back, I want to refresh this result and prevent livedata observer to be fired.
Wrap your LiveData object in a ConsumableValue like this
class ConsumableValue<T>(private val data: T) {
private var consumed = false
fun consume(block: ConsumableValue<T>.(T) -> Unit) {
if (!consumed) {
consumed = true
block(data)
}
}
}
then in viewmodel
val authenticate = MutableLiveData<Consumable<AuthenticationObject>>()
and in your fragment
viewModel.authenticate.observe(this, Observer { consumable ->
consumable.consume {
manageAuthResponse(it)
}
})
Wrap the LiveDate Like this
open class LiveEvent<T> : MediatorLiveData<T>() {
private val observers = ArraySet<ObserverWrapper<in T>>()
#MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
val wrapper = ObserverWrapper(observer)
observers.add(wrapper)
super.observe(owner, wrapper)
}
#MainThread
override fun observeForever(observer: Observer<in T>) {
val wrapper = ObserverWrapper(observer)
observers.add(wrapper)
super.observeForever(wrapper)
}
#MainThread
override fun removeObserver(observer: Observer<in T>) {
if (observers.remove(observer)) {
super.removeObserver(observer)
return
}
val iterator = observers.iterator()
while (iterator.hasNext()) {
val wrapper = iterator.next()
if (wrapper.observer == observer) {
iterator.remove()
super.removeObserver(wrapper)
break
}
}
}
#MainThread
override fun setValue(t: T?) {
observers.forEach { it.newValue() }
super.setValue(t)
}
private class ObserverWrapper<T>(val observer: Observer<T>) : Observer<T> {
private var pending = false
override fun onChanged(t: T?) {
if (pending) {
pending = false
observer.onChanged(t)
}
}
fun newValue() {
pending = true
}
}
}
then in ViewModel
val viewModel = LiveEvent<Resource<String>>()
This solution is work for me
You can check out the code in this github
I have a LoginActivity, where ViewModel is injected using dagger. LoginActivity calls an API through ViewModel upon click of a button. Meanwhile, if the screen rotates, it triggers onDestroy of LoginActivity and there, I dispose that API call. After this, in onCreate(), new instance of ViewModel is injected and because of this, my state is lost & I need to tap again in order to make API call.
Here's my LoginActivity:
class LoginActivity : AppCompatActivity() {
#Inject
lateinit var loginViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidInjection.inject(this)
val loginBinding = DataBindingUtil.setContentView<LoginBindings>(this, R.layout.activity_login)
loginBinding.loginVm = loginViewModel
loginBinding.executePendingBindings()
}
override fun onDestroy() {
super.onDestroy()
loginViewModel.onDestroy()
}
}
Here's my LoginViewModel:
class LoginViewModel(private val validator: Validator,
private val resourceProvider: ResourceProvider,
private val authenticationDataModel: AuthenticationDataModel) : BaseViewModel() {
val userName = ObservableField("")
val password = ObservableField("")
val userNameError = ObservableField("")
val passwordError = ObservableField("")
fun onLoginTapped() {
// Validations
if (!validator.isValidUsername(userName.get())) {
userNameError.set(resourceProvider.getString(R.string.invalid_username_error))
return
}
if (!validator.isValidPassword(password.get())) {
passwordError.set(resourceProvider.getString(R.string.invalid_password_error))
return
}
val loginRequest = LoginRequest(userName.get(), password.get())
addToDisposable(authenticationDataModel.loginUser(loginRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isApiCallInProgress.set(true) }
.doOnDispose {
LogManager.e("LoginViewModel", "I am disposed, save me!!")
isApiCallInProgress.set(false) }
.subscribe({ user ->
isApiCallInProgress.set(false)
LogManager.e("LoginViewModel", user.name)
}, { error ->
isApiCallInProgress.set(false)
error.printStackTrace()
}))
}
}
My BaseViewModel:
open class BaseViewModel {
private val disposables = CompositeDisposable()
val isApiCallInProgress = ObservableBoolean(false)
fun addToDisposable(disposable: Disposable) {
disposables.add(disposable)
}
fun onDestroy() {
disposables.clear()
}
}
Here's the module which provides the ViewModel:
#Module
class AuthenticationModule {
#Provides
fun provideLoginViewModel(validator: Validator, resourceProvider: ResourceProvider,
authenticationDataModel: AuthenticationDataModel): LoginViewModel {
return LoginViewModel(validator, resourceProvider, authenticationDataModel)
}
#Provides
fun provideAuthenticationRepo(): IAuthenticationRepo {
return AuthRepoApiImpl()
}
}
How can I retain my ViewModel through orientation changes. (Note: I am NOT using Architecture Components' ViewModel). Should I make my ViewModel Singleton? Or is there any other way of doing it?