0

I'm confused around member reference in Kotlin. I have a custom class that once I create an instance of it i execute api work. I keep a list of these instances of the class - once the api work has completed I want the list of the instances to be updated. In swift reference types handle this but I'm unsure how to implement in Kotlin.

So my code: MY custom class:

    class MyCustomClass(var firstName: String, var lastName:String, var profilePictureUrl:String= EMPTY_STRING){
        
        fun getUsersProfilePicture(){
//api code executed here to fetch the users profile picture
            profilePictureUrl = api result
        }
    }

when I create an instance of this object I add to an array list in my viewmodel

var myClass = MyCustomClass("firstName", "lastName")
myClass.getUsersProfilePicture()
list.add(myClass)

The api function executes fine but the instance in my list is not updated with this value. How do I update the object in my list once the api task has returned with the correct image?

nt95
  • 455
  • 1
  • 6
  • 21
  • 2
    Is `getUsersProfilePicture` async and executed in different thread? If so, try to add `@Volatile` to `profilePictureUrl`, `@Volatile var profilePictureUrl: String = ...` – IR42 Aug 07 '20 at 10:45
  • Thanks for your reply!! @Volatile was exactly what I needed! You should answer the question and I will mark it as the correct answer! Thank you so much ☺️ – nt95 Aug 07 '20 at 11:20

1 Answers1

2

It looks like you are assigning the result in different thread, add @Volatile (java volatile) so that other threads can see the changes

@Volatile var profilePictureUrl: String = ...
IR42
  • 8,587
  • 2
  • 23
  • 34