https://kotlinlang.org logo
#android
Title
# android
g

gabin

03/06/2020, 10:16 AM
Hi guys. What is the difference between liveData {} and viewModelScope {} builders in ViewModel? Does liveData survive activity recreation?
s

satyan

03/06/2020, 11:18 AM
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

gabin

03/06/2020, 12:12 PM
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

satyan

03/06/2020, 12:25 PM
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

Adam Powell

03/06/2020, 1:58 PM
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

satyan

03/06/2020, 2:04 PM
I wasn't aware of the timeout 👍 Thank you for the clarification 🙂
3 Views