What is the difference between both approaches to expose MutableLiveData [duplicate] - android

Consider the following ways to expose MutableLiveData:
Method A
class ThisViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean>
get() = _someData
}
// Decompiled Kotlin bytecode
public final class ThisViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
#NotNull
public final LiveData getSomeData() {
return (LiveData)this._someData;
}
}
Method B
class ThatViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean> = _someData
}
// Decompiled Kotlin bytecode
public final class ThatViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
#NotNull
private final LiveData someData;
#NotNull
public final LiveData getSomeData() {
return this.someData;
}
public ThatViewModel() {
this.someData = (LiveData)this._someData;
}
}
Is there a reason to use Method B over Method A?

From the Java perspective, Method A has one less field in the class, thus is "more" efficient. From the Kotlin perspective, Method B denotes a bit more clearly, that the non-mutable property is a direct reference to the mutable one. Also Kotlin is clever enough to locally access the field rather than the getter method.
Is there a reason to use Method B over Method A?
In general is merely a matter of taste. Looking at it from a micro-optimization perspective it depends on whether or not you'd also use this reference within the class itself.

Starting from Kotlin 1.4-M2 you can do simply:
private val myMutableLiveData = MutableLiveData<String>()
val myLiveData : LiveData<String> by this::myMutableLiveData
The this:: is unfortunately needed, otherwise does not compile.
I found this in Igor Wojda's answer which discusses other approaches. Unfortunately his answer in this question was deleted.

Related

Correct way to expose MutableLiveData as LiveData?

Consider the following ways to expose MutableLiveData:
Method A
class ThisViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean>
get() = _someData
}
// Decompiled Kotlin bytecode
public final class ThisViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
#NotNull
public final LiveData getSomeData() {
return (LiveData)this._someData;
}
}
Method B
class ThatViewModel : ViewModel() {
private val _someData = MutableLiveData(true)
val someData: LiveData<Boolean> = _someData
}
// Decompiled Kotlin bytecode
public final class ThatViewModelDecompiled extends ViewModel {
private final MutableLiveData _someData = new MutableLiveData(true);
#NotNull
private final LiveData someData;
#NotNull
public final LiveData getSomeData() {
return this.someData;
}
public ThatViewModel() {
this.someData = (LiveData)this._someData;
}
}
Is there a reason to use Method B over Method A?
From the Java perspective, Method A has one less field in the class, thus is "more" efficient. From the Kotlin perspective, Method B denotes a bit more clearly, that the non-mutable property is a direct reference to the mutable one. Also Kotlin is clever enough to locally access the field rather than the getter method.
Is there a reason to use Method B over Method A?
In general is merely a matter of taste. Looking at it from a micro-optimization perspective it depends on whether or not you'd also use this reference within the class itself.
Starting from Kotlin 1.4-M2 you can do simply:
private val myMutableLiveData = MutableLiveData<String>()
val myLiveData : LiveData<String> by this::myMutableLiveData
The this:: is unfortunately needed, otherwise does not compile.
I found this in Igor Wojda's answer which discusses other approaches. Unfortunately his answer in this question was deleted.

How should I get Resources(R.string) in viewModel in Android (MVVM and databinding)

I am currently using databinding and MVVM architecture for android. What would be the best way to get string resources in ViewModel.
I am not using the new AndroidViewModel component, eventbus or RxJava
I was going through the aproach of interfaces where Activity will be responsible for providing resources. But recently I found a similar question with this answer where a single class using application context is providing all resources.
Which would be the better approach? or is there something else that I can try?
You can access the context by implementing AndroidViewModel instead of ViewModel.
class MainViewModel(application: Application) : AndroidViewModel(application) {
fun getSomeString(): String? {
return getApplication<Application>().resources.getString(R.string.some_string)
}
}
You can also use the Resource Id and ObservableInt to make this work.
ViewModel:
val contentString = ObservableInt()
contentString.set(R.string.YOUR_STRING)
And then your view can get the text like this:
android:text="#{viewModel.contentString}"
This way you can keep the context out of your ViewModel
Not at all.
Resource string manipulation belongs the View layer, not ViewModel layer.
ViewModel layer should be free from dependencies to both Context and resources. Define a data type (a class or enum) that ViewModel will emit. DataBinding has access to both Context and resources and can resolve it there. Either via #BindingAdapter (if you want the clean look) or a plain static method (if you want flexibility and verbosity) that takes the enum and Context and returns String : android:text="#{MyStaticConverter.someEnumToString(viewModel.someEnum, context)}". (context is synthetic param in every binding expression)
But in most cases, String.format is enough to combine resource string format with data provided by ViewModel.
It may seem like "too much code in XML", but XML and bindings are the View layer. The only places for view logic, if you discard god-objects: Activities and Fragments.
//edit - more detailed example (kotlin):
object MyStaticConverter {
#JvmStatic
fun someEnumToString(type: MyEnum?, context: Context): String? {
return when (type) {
null -> null
MyEnum.EENY -> context.getString(R.string.some_label_eeny)
MyEnum.MEENY -> context.getString(R.string.some_label_meeny)
MyEnum.MINY -> context.getString(R.string.some_label_miny)
MyEnum.MOE -> context.getString(R.string.some_label_moe)
}
}
}
usage in XML:
<data>
<import type="com.example.MyStaticConverter" />
</data>
...
<TextView
android:text="#{MyStaticConverter.someEnumToString(viewModel.someEnum, context)}".
For more complicated cases (like mixing resource labels with texts from API) instead of enum use sealed class that will carry the dynamic String from ViewModel to the converter that will do the combining.
For simplest cases, like above, there is no need to invoke Context explicitly at all. The built-in adapter already interprets binding int to text as string resource id. The tiny inconvenience is that when invoked with null the converter still must return a valid ID, so you need to define some kind of placeholder like <string name="empty" translatable="false"/>.
#StringRes
fun someEnumToString(type: MyEnum?): Int {
return when (type) {
MyEnum.EENY -> R.string.some_label_eeny
MyEnum.MEENY -> R.string.some_label_meeny
MyEnum.MINY -> R.string.some_label_miny
MyEnum.MOE -> R.string.some_label_moe
null -> R.string.empty
}
}
Quick-and-dirty hack would be to emit a #StringRes Int directly, but that makes ViewModel dependent on resources.
"Converters" (a collection of unrelated, static and stateless functions) is a pattern that I use a lot. It allows to keep all the Android's View-related types away from ViewModel and reuse of small, repetitive parts across entire app (like converting bool or various states to VISIBILITY or formatting numbers, dates, distances, percentages, etc). That removes the need of many overlapping #BindingAdapters and IMHO increases readability of the XML-code.
an updated version of Bozbi's answer using Hilt
ViewModel.kt
#HiltViewModel
class MyViewModel #Inject constructor(
private val resourcesProvider: ResourcesProvider
) : ViewModel() {
...
fun foo() {
val helloWorld: String = resourcesProvider.getString(R.string.hello_world)
}
...
}
ResourcesProvider.kt
#Singleton
class ResourcesProvider #Inject constructor(
#ApplicationContext private val context: Context
) {
fun getString(#StringRes stringResId: Int): String {
return context.getString(stringResId)
}
}
Just create a ResourceProvider class that fetch resources using Application context. In your ViewModelFactory instantiate the resource provider using App context. You're Viewmodel is Context free and can be easily testable by mocking the ResourceProvider.
Application
public class App extends Application {
private static Application sApplication;
#Override
public void onCreate() {
super.onCreate();
sApplication = this;
}
public static Application getApplication() {
return sApplication;
}
ResourcesProvider
public class ResourcesProvider {
private Context mContext;
public ResourcesProvider(Context context){
mContext = context;
}
public String getString(){
return mContext.getString(R.string.some_string);
}
ViewModel
public class MyViewModel extends ViewModel {
private ResourcesProvider mResourcesProvider;
public MyViewModel(ResourcesProvider resourcesProvider){
mResourcesProvider = resourcesProvider;
}
public String doSomething (){
return mResourcesProvider.getString();
}
ViewModelFactory
public class ViewModelFactory implements ViewModelProvider.Factory {
private static ViewModelFactory sFactory;
private ViewModelFactory() {
}
public static ViewModelFactory getInstance() {
if (sFactory == null) {
synchronized (ViewModelFactory.class) {
if (sFactory == null) {
sFactory = new ViewModelFactory();
}
}
}
return sFactory;
}
#SuppressWarnings("unchecked")
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(MainActivityViewModel.class)) {
return (T) new MainActivityViewModel(
new ResourcesProvider(App.getApplication())
);
}
throw new IllegalArgumentException("Unknown ViewModel class");
}
}
You can use the Resource Id to make this work.
ViewModel
val messageLiveData= MutableLiveData<Any>()
messageLiveData.value = "your text ..."
or
messageLiveData.value = R.string.text
And then use it in fragment or activity like this:
messageLiveData.observe(this, Observer {
when (it) {
is Int -> {
Toast.makeText(context, getString(it), Toast.LENGTH_LONG).show()
}
is String -> {
Toast.makeText(context, it, Toast.LENGTH_LONG).show()
}
}
}
Ideally Data Binding should be used with which this problem can easily be solved by resolving the string inside the xml file. But implementing data binding in an existing project can be too much.
For a case like this I created the following class. It covers all cases of strings with or without arguments and it does NOT require for the viewModel to extend AndroidViewModel and this way also covers the event of Locale change.
class ViewModelString private constructor(private val string: String?,
#StringRes private val stringResId: Int = 0,
private val args: ArrayList<Any>?){
//simple string constructor
constructor(string: String): this(string, 0, null)
//convenience constructor for most common cases with one string or int var arg
constructor(#StringRes stringResId: Int, stringVar: String): this(null, stringResId, arrayListOf(stringVar))
constructor(#StringRes stringResId: Int, intVar: Int): this(null, stringResId, arrayListOf(intVar))
//constructor for multiple var args
constructor(#StringRes stringResId: Int, args: ArrayList<Any>): this(null, stringResId, args)
fun resolve(context: Context): String {
return when {
string != null -> string
args != null -> return context.getString(stringResId, *args.toArray())
else -> context.getString(stringResId)
}
}
}
USAGE
for example we have this resource string with two arguments
<string name="resource_with_args">value 1: %d and value 2: %s </string>
In ViewModel class:
myViewModelString.value = ViewModelString(R.string.resource_with_args, arrayListOf(val1, val2))
In Fragment class (or anywhere with available context)
textView.text = viewModel.myViewModelString.value?.resolve(context)
Keep in mind that the * on *args.toArray() is not a typing mistake so do not remove it. It is syntax that denotes the array as Object...objects which is used by Android internaly instead of Objects[] objects which would cause a crash.
I don't use data bindig but I guess you can add an adapter for my solution.
I keep resource ids in the view model
class ExampleViewModel: ViewModel(){
val text = MutableLiveData<NativeText>(NativeText.Resource(R.String.example_hi))
}
and get text on a view layer.
viewModel.text.observe(this) { text
textView.text = text.toCharSequence(this)
}
You can read more about native text in the article
For old code which you don't want to refactor you can create an ad-hoc class as such
private typealias ResCompat = AppCompatResources
#Singleton
class ResourcesDelegate #Inject constructor(
#ApplicationContext private val context: Context,
) {
private val i18nContext: Context
get() = LocaleSetter.createContextAndSetDefaultLocale(context)
fun string(#StringRes resId: Int): String = i18nContext.getString(resId)
fun drawable(#DrawableRes resId: Int): Drawable? = ResCompat.getDrawable(i18nContext, resId)
}
and then use it inside your AndroidViewModel.
#HiltViewModel
class MyViewModel #Inject constructor(
private val resourcesDelegate: ResourcesDelegate
) : AndroidViewModel() {
fun foo() {
val helloWorld: String = resourcesDelegate.string(R.string.hello_world)
}
If you are using Dagger Hilt then #ApplicationContext context: Context in your viewModel constructor will work. Hilt can automatically inject application context with this annotation. If you are using dagger then you should provide context through module class and then inject in viewModel constructor. Finally using that context you can access the string resources. like context.getString(R.strings.name)
You should use something like "UIText" sealed class to mange it all over your project(as Philip Lackner have done).
sealed class UIText {
data class DynamicString(val value:String):UIText()
class StringResource(
#StringRes val resId: Int,
vararg val args: Any
):UIText()
#Composable
fun asString():String{
return when(this){
is DynamicString -> value
is StringResource -> stringResource(resId, *args)
}
}
}
Then everyWhere in your project in place of String, use UIText.StringResource easily
Still don't find here this simple solution:
android:text="#{viewModel.location == null ? #string/unknown : viewModel.location}"

In Kotlin, how to make a property accessible by only specific type

Lets say I have a Kotlin class similar to this:
class MyKotlinExample {
val mMyString = MutableLiveData<String>()
}
MutableLiveData extends LiveData however I don't want to expose MutableLiveData to other classes. They should only see/access LiveData<String> as my special String
Is it possible, and/or good/advised etc?
You can use a backing property:
class MyKotlinExample {
private val _myString = MutableLiveData<String>()
val myString: LiveData<String>
get() = _myString
}
You can also provide an interface to your clients, which provides only LiveData<String>. Given the following classes:
interface LiveData<T> {
val value: T
}
data class MutableLiveData<T>(override var value: T) : LiveData<T>
Create the following interface/implementation:
interface MyExampleInterface {
val myString: LiveData<String>
}
class MyExampleClass : MyExampleInterface {
override val myString: MutableLiveData<String> = MutableLiveData("")
}
Internally, you can access myString as MutableLiveData, and you can pass the instance of MyExampleClass as MyExampleInterface so they can only access myString as LiveData<String>.
You should use a getter which does the cast for you:
class MyKotlinExample {
private val mMyString = MutableLiveData<String>()
fun getNonMutableLiveData(): LiveData<String> = mMyString
}
I would make the field private and expose the value like so:
class MyKotlinExample {
private val mMyString = MutableLiveData<String>()
fun getMyString(): String = mMyString.getValue()
}
Kotlin creators heard our voice and provided a simple way of doing this on Kotlin 1.7 :
private val item = MutableLiveData<Item>()
public get(): LiveData<Item>
or just:
val item = MutableLiveData <Item>()
get(): LiveData <Item>
Note: It is currently subject to opt-in and have limited support, so we will have to wait for a bit longer for stable release.
This is quite simple - you set the type of the property to LiveData<String>, but initialize it with the instance of MutableLiveData<String>:
class MyKotlinExample {
val mMyString: LiveData<String> = MutableLiveData<String>()
}

LiveData is abstract android

I tried initializing my LiveData object and it gives the error: "LiveData is abstract, It cannot be instantiated"
LiveData listLiveData = new LiveData<>();
In a ViewModel, you may want to use MutableLiveData instead.
E.g.:
class MyViewModel extends ViewModel {
private MutableLiveData<String> data = new MutableLiveData<>();
public LiveData<String> getData() {
return data;
}
public void loadData() {
// Do some stuff to load the data... then
data.setValue("new data"); // Or use data.postValue()
}
}
Or, in Kotlin:
class MyViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String> = _data
fun loadData() {
viewModelScope.launch {
val result = // ... execute some background tasks
_data.value = result
}
}
}
Since it is abstract (as #CommonsWare says) you need to extend it to a subclass and then override the methods as required in the form:
public class LiveDataSubClass extends LiveData<Location> {
}
See docs for more details
Yes, you cannot instantiate it because it is an abstract class. You can try to use MutableLiveData if you want to set values in the live data object. You can also use Mediator live data if you want to observe other livedata objects.
You need to use MutableLiveData and then cast it to its parent class LiveData.
public class MutableLiveData
extends LiveData
[MutableLiveData is] LiveData which publicly exposes setValue(T) and postValue(T) method.
You could do something like this:
fun initializeLiveData(foo: String): LiveData<String> {
return MutableLiveData<String>(foo)
}
So then you get:
Log.d("now it is LiveData", initializeLiveData("bar").value.toString())
// prints "D/now it is LiveData: bar"
I think much better way of achieving this is by using, what we call is a Backing Property, to achieve better Encapsulation of properties.
Example of usage:
private val _userPoints = MutableLiveData<Int>()// used as a private member
val userPoints: LiveData<Int>
get() {
return _userPoints
} //used to access the value inside the UI controller (Fragment/Activity).
Doing so maintains an editable MutableLiveData private to ViewModel class while, the read-only version of it is maintained as a LiveData, with a getter that returns the original value.
P.S. - notice the naming convention for both fields, using an (_) underscore. This is not mandatory but advised.

Kotlin object (singleton) with an Android Application Context [duplicate]

This question already has answers here:
Singleton with parameter in Kotlin
(14 answers)
Closed 2 years ago.
The Kotlin reference says that I can create a singleton using the object keyword like so:
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
//
}
}
However, I would like to pass an argument to that object. For example an ApplicationContext in an Android project.
Is there a way to do this?
Since objects do not have constructors what I have done the following to inject the values on an initial setup. You can call the function whatever you want and it can be called at any time to modify the value (or reconstruct the singleton based on your needs).
object Singleton {
private var myData: String = ""
fun init(data: String) {
myData = data
}
fun singletonDemo() {
System.out.println("Singleton Data: ${myData}")
}
}
Kotlin has a feature called Operator overloading, letting you pass arguments directly to an object.
object DataProviderManager {
fun registerDataProvider(provider: String) {
//
}
operator fun invoke(context: ApplicationContext): DataProviderManager {
//...
return this
}
}
//...
val myManager: DataProviderManager = DataProviderManager(someContext)
With most of the existing answers it's possible to access the class members without having initialized the singleton first. Here's a thread-safe sample that ensures that a single instance is created before accessing any of its members.
class MySingleton private constructor(private val param: String) {
companion object {
#Volatile
private var INSTANCE: MySingleton? = null
#Synchronized
fun getInstance(param: String): MySingleton = INSTANCE ?: MySingleton(param).also { INSTANCE = it }
}
fun printParam() {
print("Param: $param")
}
}
Usage:
MySingleton.getInstance("something").printParam()
There are also two native Kotlin injection libraries that are quite easy to use, and have other forms of singletons including per thread, key based, etc. Not sure if is in context of your question, but here are links to both:
Injekt (mine, I'm the author): https://github.com/kohesive/injekt
Kodein (similar to Injekt): https://github.com/SalomonBrys/Kodein
Typically in Android people are using a library like this, or Dagger, et al to accomplish parameterizing singletons, scoping them, etc.
I recommend that you use this form to pass arguments in a singleton in Kotlin debit that the object your constructor is deprived and blocked:
object Singleton {
fun instance(context: Context): Singleton {
return this
}
fun SaveData() {}
}
and you call it this way in the activity
Singleton.instance(this).SaveData()
If you looking for a base SingletonHolder class with more than one argument. I had created the SingletonHolder generic class, which supports to create only one instance of the singleton class with one argument, two arguments, and three arguments.
link Github of the base class here
Non-argument (default of Kotlin):
object AppRepository
One argument (from an example code in the above link):
class AppRepository private constructor(private val db: Database) {
companion object : SingleArgSingletonHolder<AppRepository, Database>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db)
Two arguments:
class AppRepository private constructor(private val db: Database, private val apiService: ApiService) {
companion object : PairArgsSingletonHolder<AppRepository, Database, ApiService>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db, apiService)
Three arguments:
class AppRepository private constructor(
private val db: Database,
private val apiService: ApiService,
private val storage : Storage
) {
companion object : TripleArgsSingletonHolder<AppRepository, Database, ApiService, Storage>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db, apiService, storage)
More than 3 arguments:
To implement this case, I suggest creating a config object to pass to the singleton constructor.

Categories

Resources