Hi guys. What is the difference between liveData {...
# android
g
Hi guys. What is the difference between liveData {} and viewModelScope {} builders in ViewModel? Does liveData survive activity recreation?
s
If by activity re-creation you mean when an activity is recreated after a process death, no. However, if you mean configuration change (rotation, resize, etc), yes. I've never seen
viewModelScope{}
but
livedata{}
is used to create a Livedata using the ViewModel coroutine scope. (Using
emit
to emit values or
emitSource
to emit values from another Livedata) The
viewmodelScope
is a CoroutineScope scoped by the ViewModel lifecycle.
g
Yep, I mean exactly configuration change. I know that
viewModelScope{}
survives it, but I am not sure about
livedata{}
. Lets say I made a network request inside
livedata{}
and rotated screen couple of times - will the result arrive to observer ? Will it be cancelled if viewModel is destroyed and I moved to another activity?
s
The ViewModel itself survive configuration change. So with livedata you'll expose a Livedata and when the activity state will be started it's going to observe the value of the Livedata.
a
The block for
liveData {}
will stay alive for as long as the resulting
LiveData
has active observers, plus a configurable timeout. The default is non-zero and you can change it with a parameter to the
liveData {}
builder. Therefore if you start re-observing the same
LiveData
instance after a config change before the timeout expires, yes, the work happening in that block will continue.
s
I wasn't aware of the timeout 👍 Thank you for the clarification 🙂