Leroy Ramaphoko
Leroy Ramaphoko

Reputation: 31

Why is the Coroutine running once?

I'm having a situation whereby the coroutine is executing once. The second time I call the fetchUser function it does nothing:

class UserViewModel(application: Application): AndroidViewModel(application) {
    private val repository = UserRepository(application)

    private val _user = MutableLiveData<User>()
    val user: LiveData<User>
        get() = _user


    fun fetchUser(userId: String) = viewModelScope.launch(Dispatchers.IO)  {
        val result = repository.getUser(userId)

        if (result.isSuccessfulWithData) {
            _user.postValue(result.data?.user)
        }
    }
}

Upvotes: 0

Views: 613

Answers (1)

Sergio
Sergio

Reputation: 30735

There is nothing wrong with your code, each time you fetchUser a new coroutine is launched and code inside it should execute each time. You can add Log at the beginning of the coroutine to check if the coroutine is launched in the Logcat. If repository.getUser(userId) is a suspend function I would also remove Dispatchers.IO context when calling viewModelScope.launch(Dispatchers.IO) because it is safe to call suspend function in the Dispatchers.Main context (by default viewModelScope has Dispatchers.Main context). So the code with the Log and improvement will look like the following:

class UserViewModel(application: Application): AndroidViewModel(application) {
    private val repository = UserRepository(application)

    private val _user = MutableLiveData<User>()
    val user: LiveData<User>
        get() = _user


    fun fetchUser(userId: String) = viewModelScope.launch  {
        Log.d("UserViewModel", "fetchUser called")
        val result = repository.getUser(userId)

        if (result.isSuccessfulWithData) {
            _user.postValue(result.data?.user)
        }
    }
}

Upvotes: 1

Related Questions