Reputation: 69
var value: String = ""
fun getValue(key: String, lifecycleOwner: LifecycleOwner): String {
val data = dataStore.data.map { pre ->
pre[preferencesKey<String>(key)]
}
data.asLiveData().observe(lifecycleOwner, Observer {
value = it ?: "noData"
Log.i("MONO", "A | $value")
})
return value
}
return log data is true but in return value data is null
Upvotes: 0
Views: 853
Reputation: 18627
I don't know Android, but a quick Google indicates that the LiveData.observe()
method adds an observer.
This is clearly using the standard observer pattern that you find in many languages and frameworks. The observer is informed (i.e. called) at the relevant time(s).
Note that the observer might not be called immediately. In this case, it's clearly not: the observe()
call returns after adding the observer, while your value
is still null
; and your getValue()
method returns that null. At some later point, the observer may be called and set value
, but by then nothing cares about it.
I don't know LiveData well enough to advise on what to do, but I notice it has a getValue()
method that might do what you want, if the value is available immediately.
If not, you'll have to block until the observer is called. This question would seem to indicate one way of doing that. (The answer is in Java, but you can probably get the idea from that.)
Upvotes: 1