Home > OS >  LiveData observer not triggered
LiveData observer not triggered

Time:08-05

I want to navigate to an other Fragment when the user selcts a value (player id) in the AlertDialog. I use this change to the id to trigger the navigation. Unfortunately the observer of this property doesn't get triggerd. Please see the following code:

SelectCharacterDialogFragment.kt

@AndroidEntryPoint
class SelectCharacterDialogFragment : DialogFragment() {
    val viewModel: WelcomeViewModel by viewModels()

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        super.onCreateDialog(savedInstanceState)
        val names = arguments?.getStringArrayList("names")
        val ids = arguments?.getIntegerArrayList("ids")

        val dialogBuilder = MaterialAlertDialogBuilder(requireContext())
            .setTitle("Choose a character")
            .setItems(names!!.toTypedArray()) { dialog, which ->
                val playerId = ids?.get(which)
                Timber.d("Selected player id: %d", playerId)
                viewModel.setActivePlayerId(playerId!!)
            }
        return dialogBuilder.create()

    }
}

WelcomeViewModel.kt

@HiltViewModel
class WelcomeViewModel @Inject constructor(private val repository: PlayerRepository) : ViewModel() {

    private val _activePlayerId = MutableLiveData<Int>()
    val playerId:LiveData<Int> =_activePlayerId

    fun setActivePlayerId(playerId: Int){
        setActivePlayer(playerId)
        _activePlayerId.value =playerId
    }

    private fun setActivePlayer(playerId: Int) {
        viewModelScope.launch {
            repository.setActivePlayer(playerId)
            Timber.d("Active player set to id: %d", playerId)
        }
    }
}

WelcomeFragment.kt

@AndroidEntryPoint
class WelcomeFragment : Fragment() {
    private val viewModel: WelcomeViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        viewModel.playerId.observe(viewLifecycleOwner){
            Timber.d("Observing active player id: %d", it)
            findNavController().navigate(
                WelcomeFragmentDirections.actionWelcomeFragmentToNavigationPlayer()
            )
        }
    }
}

The last log output I see is from the method WelcomeViewModel#setActivePlayer(playerId: Int). Maybe it's obvious but I just can't figure out what's wrong with the code.

CodePudding user response:

You've to use shared viewmodel.

Update your fragment and dialog as well

val viewModel: WelcomeViewModel by activityViewModels()
  • Related