MutableLiveData, LiveData List empty or add item first position - kotlin

I don't quite understand the behavior of MutableLiveData or I can't find the proper documentation.
But I need help.
I need to add an element to the first position of the array and tried with "plus" but it doesn't work properly. Or is there a way to add multiple elements of an array in the first position?
_series.value = _series.value?.plus(it) // ??? 11111111
I can't figure out how to delete all the elements of the array, I did it with
_series.value = null // ??? 2222222
_series.value = ArrayList() /// ??? 2222222
but I don't think it is the best way to do it.
class SerieViewModel(val database: SerieDatabaseDao) : ViewModel() {
private val _series = MutableLiveData<List<Serie>?>()
val series: LiveData<List<Serie>?>
get() = _series
fun fetchSeries(code: String) {
viewModelScope.launch {
try {
val response = CodesApi.retrofitService.getSeries(code)
val series = response.body()?.data
series?.forEach {
_series.value = _series.value?.plus(it) // ??? 11111111
}
}
} catch (e: Exception) {
Log.d(TAG, "fetchSeries: ${e.message}")
}
}
}
fun clearDb() = viewModelScope.launch {
database.clear()
_series.value = null // ??? 2222222
_series.value = ArrayList<Serie>() /// ??? 2222222
}
thanks

You are storing a List<Serie?> which is fine thats what you should do, but you can't add elements to List, you need to convert List to ArrayList and add elements to the ArrayList than update the MutableLiveData, follow the code below.
to clear all the elements from the List you can set the value to emptyList(), follow the code below.
Note: Take a look about the difference between List, ArrayList, Array in kotlin they are not the same
class SerieViewModel(val database: SerieDatabaseDao) : ViewModel() {
private val _series = MutableLiveData<List<Serie>?>()
val series: LiveData<List<Serie>?>
get() = _series
fun fetchSeries(code: String) {
viewModelScope.launch {
try {
val response = CodesApi.retrofitService.getSeries(code)
val series = response.body()?.data
val liveDataSeries =
if (_series.value == null) emptyList<Serie>() // set the array list to empty if _series.value is null
else ArrayList(_series.value) // else: add _series.value elements to the array list
series?.forEach {
liveDataSeries.add(it) // add each serie to the array list
}
_series.value = liveDataSeries // update _series.value
} catch (e: Exception) {
Log.d(TAG, "fetchSeries: ${e.message}")
}
}
}
fun clearDb() = viewModelScope.launch {
database.clear()
_series.value = emptyList()
}
}

Related

find value in arraylist in kotlin

Hey I am working in kotlin. I am working on tree data structure. I added the value in list and now I want to find that value and modified their property. But I am getting the error.
VariantNode, StrengthNode, ProductVariant
StrengthNode.kt
class StrengthNode : VariantNode() {
var pricePerUnit: String? = null
var defaultValue = AtomicBoolean(false)
}
ActivityViewModel.kt
class ActivityViewModel : ViewModel() {
var baseNode: VariantNode = VariantNode()
private val defaultValueId = "12643423243324"
init {
createGraph()
}
private fun createGraph() {
val tempHashMap: MutableMap<String, VariantNode> = mutableMapOf()
val sortedList = getSortedList()
sortedList.forEach { productVariant ->
productVariant.strength?.let { strength ->
if (tempHashMap.containsKey("strength_${strength.value}")) {
baseNode.children.contains(VariantNode(strength.value)) // getting error
return#let
}
val tempNode = StrengthNode().apply {
value = strength
pricePerUnit = productVariant.pricePerUnit?.value
if (productVariant.id == defaultValueId) {
defaultValue.compareAndSet(false, true)
}
}
baseNode.children.add(tempNode)
tempHashMap["strength_${strength.value}"] = tempNode
}
productVariant.quantity?.let { quantity ->
if (tempHashMap.containsKey("strength_${productVariant.strength?.value}_quantity_${quantity.value}")) {
return#let
}
val tempNode = QuantityNode().apply {
value = quantity
}
val parent =
tempHashMap["strength_${productVariant.strength?.value}"] ?: baseNode
parent.children.add(tempNode)
tempHashMap["strength_${productVariant.strength?.value}_quantity_${quantity.value}"] =
tempNode
}
productVariant.subscription?.let { subscription ->
val tempNode = SubscriptionNode().apply {
value = subscription
}
val parent =
tempHashMap["strength_${productVariant.strength?.value}_quantity_${productVariant.quantity?.value}"]
?: baseNode
parent.children.add(tempNode)
}
}
baseNode
}
}
I am getting error on this.
I want to find that node value and modified other property.
Your class VariantNode only has a single no-arg constructor, but you're trying to call it with arguments, hence the error
Too many arguments for public constructor VariantNode() defined in com.example.optionsview.VariantNode
Either you have to provide a constructor, that matches your call, e.g.
open class VariantNode(var value: ProductValue?) {
var children: MutableList<VariantNode> = arrayListOf()
}
or you need to adjust your code to use the no-arg constructor instead.
val node = VariantNode()
node.value = strength.value
baseNode.children.contains(node)
Note however, that your call to contains most likely will not work, because you do not provide a custom implementation for equals. This is provided by default, when using a data class.
If you just want to validate whether baseNode.children has any element, where value has the expected value, you can use any instead, e.g.:
baseNode.children.any { it.value == strength.value }

Why 'add' method doesn't work for mutableListOf()?

I have my own converter from Strings to List
object TypeConverter {
fun stringToListLong(text: String): List<Long> {
val listLong = mutableListOf<Long>()
val listString = text.split(",").map { it.trim() }
listString.forEach {
listLong.add(it.toLong())
}
return listLong
}
}
Then when I try to use it like below it shows the error(Unresolved reference: add)
val someString = "something"
var ids = TypeConverter.stringToListLong(someString)
ids.add(some long value)
Why?
You're returning a List<>, so ids is a List<>, therefore it does not have mutation operations. Make stringToListLong return MutableList<Long>.

Kotlin general setter function

I am new to kotlin. I wonder if this is possible
I wish to create a function that will change the value of the properties of the object and return the object itself. The main benefit is that I can chain this setter.
class Person {
var name:String? = null
var age:Int? = null
fun setter(propName:String, value:Any): Person{
return this.apply {
try {
// the line below caused error
this[propName] = value
} catch(e:Exception){
println(e.printStackTrace())
}
}
}
}
//usage
var person = Person(null,null)
person
.setter(name, "Baby")
.setter(age, 20)
But I get error "unknown references"
This question is marked as duplicate, however the possible duplicate question specifically want to change the property of "name", but I wish to change anyProperty that is pass from the function to object. Can't seem to connect the dot between two questions. #Moira Kindly provide answer that explain it. thankyou
Why not just simplify your answer to
fun setter(propName: String, value: Any): Person {
val property = this::class.memberProperties.find { it.name == propName }
when (property) {
is KMutableProperty<*> ->
property.setter.call(this, value)
null ->
// no such property
else ->
// immutable property
}
}
Java reflection isn't needed, its only effect is to stop non-trivial properties from being supported.
Also, if you call it operator fun set instead of fun setter, the
this[propName] = value
syntax can be used to call it.
After googling around, I think I can provide an answer, but relying on java instead of kotlin purely. It will be great if someone can provide a better answer in kotlin.
class Person(
var name: String,
val age: Int
){
fun setter(propName: String, value: Any): Person{
var isFieldExistAndNotFinal = false
try{
val field = this.javaClass.getDeclaredField(propName)
val isFieldFinal = (field.getModifiers() and java.lang.reflect.Modifier.FINAL == java.lang.reflect.Modifier.FINAL)
if(!isFieldFinal) {
// not final
isFieldExistAndNotFinal = true
}
// final variable cannot be changed
else throw ( Exception("field '$propName' is constant, in ${this.toString()}"))
} catch (e: Exception) {
// object does not have property
println("$e in ${this.toString()}")
}
if(isFieldExistAndNotFinal){
val property = this::class.memberProperties.find { it.name == propName }
if (property is KMutableProperty<*>) {
property.setter.call(this, value)
}
}
return this;
}
}
usage like this
person
.setter(propName = "age", value = 30.00)
.setter(propName = "asdf", value = "asdf")
.setter(propName = "name", value = "A Vidy")
You have error because when you do this[propName] = value you are trying to use this as a list, but it is not a list, it is a Person and it doesn't overload the [] operator.
What you can do is to add a check for the property that is setted:
class Person {
privavar name:String? = null
var age:Int? = null
fun setter(propName:String, value:Any): Person{
return this.apply {
if (propName == "name" && value is String?) {
it.name = value as String?
} else if (propName == "age" && value is Int?) {
it.age = value as Int?
} else {
// handle unknown property or value has incorrect type
}
}
}
}
Another more dynamic solution without reflection:
class Person {
private var fields: Map<String, Any?> = HashMap()
fun setter(propName:String, value:Any): Person{
return this.apply {
it.fields[propName] = value;
}
}
fun getName() = fields["name"]
}
If you want to get rid of the getters as well then you need to use reflection.

Check for null in map function in Kotlin

I'm new to Kotlin and I want to map an object (ProductVisibility) base on another one (fmpProduct). Some object can't be converted so I need to skip them on some condition.
I wanted to know if there's a better way to do this than what I did with the filter and the "!!" I feel that it's hacked. Am I missing something ?
val newCSProductVisibility = fmpProducts
.filter { parentIdGroupedByCode.containsKey(it.id) }
.filter { ProductType.fromCode(it.type) != null } //voir si on accumule les erreus dans une variable à montrer
.map {
val type = ProductType.fromCode(it.type)!! //Null already filtered
val userGroupIds = type.productAvailabilityUserGroup.map { it.id }.joinToString(",")
val b2bGroupIds = type.b2bUserGroup.map { it.id }.joinToString { "," }
val b2bDescHide = !type.b2bUserGroup.isEmpty()
val parentId = parentIdGroupedByCode[it.id]!! //Null already filtered
CSProductDao.ProductVisibility(parentId, userGroupIds, b2bGroupIds, b2bDescHide)
}
edit: updated the map access like comment suggested
Use mapNotNull() to avoid the filter()s and do everything in the mapNotNull() block, then the automatic typecast to non-null type works.
Example:
fun f() {
val list = listOf<MyClass>()
val v = list.mapNotNull {
if (it.type == null) return#mapNotNull null
val type = productTypeFromCode(it.type)
if (type == null) return#mapNotNull null
else MyClass2(type) // type is automatically casted to type!! here
}
}
fun productTypeFromCode(code: String): String? {
return null
}
class MyClass(val type: String?, val id: String)
class MyClass2(val type: String)

Split algorithm and view part using a Strategy Pattern in Kotlin

This is the code I would like to refactor:
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get Post object and use the values to update the UI
requestsUsers?.clear()
val match = dataSnapshot.children
val keysArray = KeysHandler()
if (match != null) {
for (data in match) {
keysArray.addToList(data.key)
}
if (keysArray.list.size > 0) {
repeat(keysArray.list.size) { i ->
val onlineMatch = dataSnapshot.child(keysArray.getElement(i)).getValue(OnlineMatch::class.java)!!
onlineMatch.key = keysArray.list[i]
requestsUsers.add(onlineMatch)
}
}
}
//Updating GUI
updateRequests()
}
As you can see I am downloading data in an array called match. Then I parse the same array obtaining an array of keys (keysArray). Then I add a specific element of the keys array to another array (requestsUser).
Considering that this algorithm could be changed I would like to incapsulate the algorithm part in another class. I read somewhere that in these kind of situation the best thing to do is to use a Strategy Pattern, but I am working in kotlin. How could I implement a Strategy Pattern in Kotlin?
It should be similar to Java.
Suppose the type of requestsUsers is ArrayList<RequestsUser>.
Create the strategy interface.
interface Strategy {
fun getRequestsUsers(dataSnapshot: DataSnapshot): ArrayList<RequestsUser>
}
Implement the interface.
class StrategyImpl: Strategy {
override fun getRequestsUsers(dataSnapshot: DataSnapshot): ArrayList<RequestsUser> {
val match = dataSnapshot.children
val keysArray = KeysHandler()
val requestsUsers = arrayListOf<RequestsUser>()
if (match != null) {
for (data in match) {
keysArray.addToList(data.key)
}
if (keysArray.list.size > 0) { //this line can be omitted
repeat(keysArray.list.size) { i ->
val onlineMatch = dataSnapshot.child(keysArray.getElement(i)).getValue(OnlineMatch::class.java)!!
onlineMatch.key = keysArray.list[i]
requestsUsers.add(onlineMatch)
}
}
}
return requestsUsers
}
}
Declare the strategy in your class
var strategy = StrategyImpl() //make it var so that it can be changed
Finally, use strategy to get the list of data and add to the list.
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get Post object and use the values to update the UI
requestsUsers?.clear()
requestsUsers?.addAll(strategy.getRequestsUsers(dataSnapshot))
//Updating GUI
updateRequests()
}
}