Home > Net >  Is it possible to change the variable value for a coroutine started during ViewModel initialization
Is it possible to change the variable value for a coroutine started during ViewModel initialization

Time:01-08

I have a Kotlin coroutine that I initialize in a Viewmodel class. Something like this

init {
     viewModelScope.launch {
        person.retrievePersonsWithId(<ID VARIABLE>).collect {
            _persons.value = it
        }
    }
}

Is this <ID VARIABLE> changeable based on UI. What I want to be able to do is have this Kotlin coroutine continuously running. When the UI text changes be able to change that <ID VARIABLE> so that the coroutine automatically picks it up without having to cancel the above coroutine and recreate a new one.

CodePudding user response:

First, we need a way to observe changes to this <ID VARIABLE>, preferable in a form of another flow of ids. There are multiple ways to create such flow, it depends on your specific case. One of the easiest is to store the id inside a MutableStateFlow:

private val idFlow = MutableStateFlow(<initial value>)

// change ID value:
idFlow.value = 42

We use this idFlow as a source of IDs. Then we need to use flatMapLatest to re-initialize another, resulting flow using retrievePersonsWithId() whenever the ID changes:

idFlow.flatMapLatest { person.retrievePersonsWithId(it) }.collect {
    _persons.value = it
}
  •  Tags:  
  • Related