0

I'm currently using StateFlow and SharedFlow on Android.

When subscribe to SharedFlow in ViewModel in Activity, using repeatOnLifecycle() to cancel and resume subscription according to lifecycle.

The first time. run the app in this state, show toast message of '100', and the moment change the app to the background state and look at the screen again, show toast message of 100 again.

I don't want this to happen.

If the app is the same value when it comes back from the background, I don't want to see the toast message. How should I deal with this??

In Activity

lifecycleScope.launch {             
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        mainViewModel.a.collect {  
            Toast.makeText(this@MainActivity, it, Toast.LENGTH_SHORT).show() 
        }                
    }             
}         

ViewModel

@HiltViewModel
class MainViewModel @Inject constructor() : ViewModel() {
    private val _a = MutableSharedFlow<Int>(replay = 1)
    val a = _a.asSharedFlow()

    init {
        viewModelScope.launch {
            _a.emit(100)
        }
    }
}

1 Answers1

0

That's the behavior of SharedFlow's they can emit same values, if you want the collector to only collect unique values , use a StateFlow instead.

zaid khan
  • 825
  • 3
  • 11