Transformations.map not getting triggered immediately

440 Views Asked by At

Here's the snippet to demonstrate the problem:

ViewModel code:

class SampleViewModel : ViewModel() {
    private String someData = ""
    private lateinit var _selectedString: MutableLiveData<String?>
    val selectedString: LiveData<String?> get() = _selectedString

    fun setSource(someData : String) {
        this.someData = someData
        _selectedString = Transformations.map(source) {
           performChange()
           it
        } as MutableLiveData<String?>
    }

    fun loadScreen() {
        _selectedString.value?.let {
            //do something
        }
    }
}

Fragment Code:

class SampleFragment : Fragment() {

    private val viewModel: SampleViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    if (savedInstanceState == null) {
        viewModel.setSource("Hey There")
    }
    wireObservers()
    viewModel.loadScreen()
    }

    private fun wireObservers() {
        viewModel.selectedString.observe(viewLifeCycleOwner) {
            //dummy observer because Transformations doesn't work unless there is an 
            active observer
        }
    }
}

PROBLEM: Before the mapFunction in Transformations.map is executed, the viewModel.loadScreen is getting called and hence nothing is happening because _selectedString will be null unless the Transformations.map is executed.

Expected Behaviour: Transformations.map which is initialized in setSource() method should apply the Transformation right after the source livedata changes and not after the viewModel.loadScreen() is called.

0

There are 0 best solutions below