I am new to LiveData thing in general and I am having a hard time understanding the difference between LiveData<String>() and LiveData<String?>(). I used them interchangeably and nothing seams to break. I know that LiveData.getValue() is marked with @Nullable in Java, so we end up getting String? anyway. So what makes LiveData<String?>() different from LiveData<String>()?
What is the difference between LiveData<String>() and LiveData<String?>()
424 Views Asked by Khalida Aliyeva At
2
There are 2 best solutions below
5
Александр Волошиновский
On
LiveData<String?>() meens that livedata can store null, read please this article to be fully informed: https://kotlinlang.org/docs/null-safety.html
Related Questions in ANDROID
- Creating global Class holder
- Flutter + Dart: Editing name of a tab shows up a black screen
- android-pdf-viewer Received status code 401 from server: Unauthorized
- Sdk 34 WRITE_EXTERNAL_STORAGE not working
- ussd reader in Recket Native module
- Incorrect display of LinearGradientBrush in IOS
- The Binary Version Of its metadata is 1.8.0, expected Version is 1.6.0 build error
- I can't make TextInput to auto expand properly in Android
- Creating multiple instances of a class with different initializing values in Flutter
- How to create a lottie animation
- making android analyze with coverity sast tool
- Flutter plugin development android src not opening after opening example
- I initialize my ViewModel in the Activity with several fragments as tabs, but the fragments(tabs) return null for the updated livedata
- Node.js Server + Socket.IO + Android Mobile Applicatoin XHR Polling Error...?
- How I can use the shared preferences class?
Related Questions in KOTLIN
- getting error when trying to launch kotlin jar file that use supabase "java.lang.NoClassDefFoundError"
- ussd reader in Recket Native module
- making android analyze with coverity sast tool
- Jooq - Insert does not update object with generated id
- Doesn't work TrafficStats.clearThreadStatsTag() in Kotlin
- Difference between map and function returning when in Kotlin
- Every Time i run the app it gives me an error related to gradle
- How Do I Create A Path In The pubspec.yaml File?
- Android jetpack compose webview, image selector not works
- Why doesn't CIOEngine have a dispatcher in kotlin script?
- preventing duplicate text
- onCompletion(mp: MediaPlayer?) is unintentionally called after USB storage is connected
- When using a Room database on an Android application, is it possible to pre-populate data
- Jetpack compose - how I can hookup LiveData property from ViewModel with TextField in activity?
- Failed to getEnergyData
Related Questions in ANDROID-LIVEDATA
- I initialize my ViewModel in the Activity with several fragments as tabs, but the fragments(tabs) return null for the updated livedata
- Filtering and managing LiveData
- Multiple MutableLiveData change results in a single MutableLiveData
- Why LazyColumn does not recompose when data updets JetPack compose
- How to collect multiple liveDatas as one single Flow?
- LiveData Observer is not working in jetpack compose
- Activity unable to observe second livedata object within viewmodel
- Unable to update recycler view using live data, room database, diff utils, mvvm architecture
- What is a possible issue with LiveData that doesn't return a value?
- LiveData initialization
- LiveData observer never getting removed between shared ViewModel
- How to write unit test for Android ViewModel & LiveData?
- Python can't read DDE linked datas on excel file
- Error with viewmodel facotry and viewmodel module injecting thorugh Dagger, UninitializedPropertyAccessException: lateinit property viewModelFactory
- Can't fetch the data of type list from RoomDB. I had used TypeConverter also
Related Questions in NULLABLE
- Validation error occurs when binding DateTime? with MudBlazor's MudTextField
- Issue with nullable reference types in C# 8
- Spark Not Null constrains in combination with badrecordspath for reading (delta) tables
- How can I mark a c# function by a third party as library as nullable
- Why doesn't kotlinx.datetime.LocalTime XML deserialization with Jackson use default kotlin values?
- Rules of Unbounded type parameters in Generics ( C# )
- Behavior of Passing Nullable<T> into a Generic Method that accepts T?
- Non-nullable types set to null by libraries
- openapi-generator does not generate JsonNullable<?> for Java Client
- C# - How to override null value in JsonConvert.SerializeObject output
- Nullable object must have a value based on equation
- How do I add the Nullable context in Unity?
- How to SQL join when join-id is nullable
- Deserializing objects from an API when it's unclear which properties are nullable on the JSON response
- Kotlin is there a map function for nullable values
Related Questions in NULLABILITY
- Kotlin - Issue with Elvis operator
- Is it possible to create a String extension `isEmptyOrNull` in dart?
- How do I resolve nullability of reference types in type of parameter warnings?
- Filtering for Non-Nullable Strings in C# Lists
- Nullability Check: Difference between literals and objects, or: "Why does "if(is null) [..]" work for object? but not for int?/long?/.. ?"
- Vector of 'nullable' HashMaps in rust
- Nullability of generic type arguments
- Making the C# compiler aware that a null-oblivious method may return null?
- Stop nullability warnings from entity framework queries that include nullable navigation properties
- What is the difference between LiveData<String>() and LiveData<String?>()
- Is there a way to indicate to C# nullability analysis that an instance variable will never be null after a certain method runs?
- Make the Intellisense nullability warning conditional, similar to Dictionary<string, string>.TryGetValue(...)
- How to Solve Event Hander Nullable Warning Problem
- Is it considered bad practice to use a "string?" parameter?
- Can't assign non-nullable type to a nullable one
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
This ended up a bit long but I hope it covers everything!
A
LiveDatais meant to beobserved. The observer receives data, and theLiveData's type says what type that data is. ALiveData<String>will only supply non-nullStrings to its observers. ALiveData<String?>can supplyStrings and nulls.Which of those you want depends on what you're doing! Do you need to supply nulls, e.g. for some kind of missing value or whatever? Should they be part of your data? If not, like in any other situation, avoid making the type nullable unless it needs to be.
When an observer first
observes aLiveData, it receives the current value. That way it can immediately handle the current data, update to display the current state, etc. But it's possible for aLiveDatato have no value initially:The first one there has an initial value. If you observe it, and that value hasn't been updated, the observer will immediately be called with
"hi"for its parameter.The second one has no value. If you observe that, the observer won't be called until a value is set on it. This is useful when you don't actually have any initial data - you can still set up your observer, and nothing will happen until some data is actually pushed.
The third one is the same as the first - it's a nullable
String?but with a value of null. That's still a value so if youobserveit, the observer will immediately be called with that null. It's still a piece of data your observer has to react to and process.The last one is nullable but with no initial value. Like the second one, this means there's nothing for the observer to receive at first - but when it does have a value set on it, it could be a null. null is just another kind of value!
But if you go poking around at the
LiveData'svalueproperty, instead of interacting with it throughobserve, then that no value state is represented internally by null. Java (or at least the version Android targets) doesn't really have a representation of no value separate from null, so that's just how they have to do things. It just doesn't publish anything until you explicitly set a value on it.So for each of these:
if you read their
valuein this state, it will be null for all of them. One explicitly has a value of null set on it, the others are both empty. This also means that even thoughemptyLiveData's type is non-null, itsvalueproperty can be null, just because of this "can be empty" situation which is true for allLiveDataobjects. The nullability of the type is purely about what gets passed to observers.You generally shouldn't be reading
valueanyway, except internally (wherever you're actually setting the value). Everything else should be interacting with thatLiveDataby observing it and reacting to the values that are published, and those values will be whatever type (nullable or not) that you specified