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 answers
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
- Delay in loading Html Page(WebView) from assets folder in real android device
- MPAndroidChart method setWordWrapEnabled() not found
- Designing a 'new post' android activity
- Android :EditText inside ListView always update first item in the listview
- Android: Transferring Data via ContentIntent
- Wrong xml being inflated android
- AsyncTask Class
- Unable to receive extras in Android Intent
- Website zoomed out on Android default browser
- Square FloatingActionButton with Android Design Library
- Google Maps API Re-size
- Push toolbar content below statusbar
- Android FragmentPagerAdapter Circular listview
- Layout not shifting up when keyboard is open
- auDIO_OUTPUT_FLAG_FAST denied by client can't connect to localhost
Related Questions in KOTLIN
- Volatile properties in Kotlin?
- Using multiple JVM languages in the same project
- Kotlin - IntelliJ Project Setup
- Kotlin let analogue which returns the receiver
- Kotlin 'when' statement vs Java 'switch'
- Use Kotlin extension in android java class
- Kotlin stub/placeholder function for unimplemented code
- Partial class delegation in Kotlin
- SugarORM + Kotlin: Unresovled reference "listAll"
- Kotlin JS - string to number conversion?
- Where is the old Kotlin specification hosted?
- Kotlin JS - Accessing HTML DOM properties
- Access property delegate in Kotlin
- Kotlin-JS interop - using language constructs
- Does "internal" visibility modifier in Kotlin work yet?
Related Questions in ANDROID-LIVEDATA
- Observe LiveData from JobService
- LiveData List doesn't update when updating database
- MutableLiveData with Kotlin multiple layler Generic not work
- Reload RecyclerView after data change with Room, ViewModel and LiveData
- setValue and postValue on MutableLiveData in UnitTest
- How can I use a view model, with sqlite and a broadcast receiver to update the UI?
- How to convert LiveData<List<Foo>> into LiveData<List<Bar>>?
- LiveData onResume not fetching new value, on pre Android 7 SDKs
- Nullability and LiveData with Kotlin
- LiveData does not call LifecycleRegistryOwner if standard Fragment is used
- LifecycleRegistryOwner class is deprecated
- Query in DAO is always returns null eventhough data exists in Database in Android-Room-LiveData-Fragments
- How to observe LiveData created by Service from UI/MainActivity/Fragments?
- Changes to LiveData of composite objects
- When unit testing a viewmodel with a repository that returns a flow, an error happen when converting it to a livedata
Related Questions in NULLABLE
- how to convert date time if passing null value in date field
- When I try to map the properties for an entity (Entity Framework), I get the error the type '__' must be a non-nullable value type
- Java 8 Optional.ifPresent is my code wrong or is it eclipse?
- Type checking and iterating through ANY array in Swift
- Giving a string a null value
- Cannot cast DBNull.Value to type System.DateTime
- Is the C# compiler optimizing nullable types?
- FindBugs Ignores @Nullable
- How to write SQL statement with dynamic where clause?
- Why is my Nullable(Of Int32) = 0 after I set it to Nothing?
- Select SQL with nullable integer variable and "in" at the where clause in asp dataset
- How do I pass Nullable<Boolean> value to CommandParameter?
- Nullable(Of ) is not set to Nothing in conditional ternary operator
- How to convert an int array to a nullable int array?
- How to use generic and Nullable<T> types in Dapper for materialization?
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
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?
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)
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