Code: Select all
@AndroidEntryPoint
class FragmentA : Fragment() {
private val viewModel: ViewModelA by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentBinding.inflate(layoutInflater, container, false)
viewModel.state.observe(viewLifecycleOwner) {
it?.let {
binding.fragmentInt.text = it.toString()
}
}
binding.fragmentInt.setOnClickListener {
findNavController().navigate(
FragmentADirections.actionFragmentAToFragmentB()
)
}
return binding.root
}
}
@HiltViewModel
class ViewModelA @Inject constructor(
private val intRepository: IntRepository
) : ViewModel() {
private val _state: MutableLiveData = MutableLiveData(null)
val state: LiveData = _state
init {
viewModelScope.launch {
intRepository.observeScreenState().collect {
_state.value = it
}
}
intRepository.updateScreenState(1)
}
}
@AndroidEntryPoint
class FragmentB : Fragment(R.layout.fragment) {
private val viewModel: ViewModelB by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentBinding.inflate(layoutInflater, container, false)
viewModel.state.observe(viewLifecycleOwner) {
it?.let {
binding.fragmentInt.text = it.toString()
}
return binding.root
}
}
@HiltViewModel
class ViewModelB @Inject constructor(
private val intRepository: IntRepository
) : ViewModel() {
private val _state: MutableLiveData = MutableLiveData(null)
val state: LiveData = _state
init {
viewModelScope.launch {
intRepository.observeScreenState().collect {
_state.value = it
}
}
intRepository.updateScreenState(6)
}
}
class IntRepository @Inject constructor() {
private val screenStateFlow = MutableStateFlow(null)
fun observeScreenState(): Flow = screenStateFlow.asStateFlow()
fun updateScreenState(value: Int) {
screenStateFlow.value = value
}
}