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 ofLiveData
in yourViewModel
class to send only new updates after subscription.This
LiveData
extension only calls the observable if there's an explicit call tosetValue()
orcall()
.