So I want to use mutableStateOf in my ViewModel li...
# compose
h
So I want to use mutableStateOf in my ViewModel like this:
Copy code
private var _state: State by mutableStateOf(Loading)
    override val state: State = _state

    fun onLoadClicked() {
        _state = Loading
        viewModelScope.launch {
            _state = when (val content: Content? = loadData()) {
                null -> Error
                else -> PresentData(content)
            }
        }
    }
So now I would like to test the behaviour of onLoadClicked. But I do not know how to verify that calling that function sets the state to Loading and than to PresentData/Error. I could observe a liveData and remember all states is was set to but how do I do it with mutableStateOf?
1
m
I think you can test it with
runBlockingTest { }
and use
pauseDispatcher()
(then it will not go through
launch { }
immediately, so you can test the
Loading
state. Then invoke
advanceUntilIdle()
and check the state after that.
h
thanks, I will try that 🙏
works like a charm 🙂
🦜 1
Copy code
runBlockingTest(testDispatcher) {
            pauseDispatcher()

            sut.onReloadClick()
            sut.state.shouldBeTypeOf<Loading>()

            advanceUntilIdle()
            sut.state.shouldBeTypeOf<PresentData>()
        }
today i learned 1
1
👍 1
a
Btw you don’t need two properties. You can just write:
Copy code
override var state: State by mutableStateOf(Loading)
    private set
today i learned 2