What I would like to do is make a method continually run in the background and, on each run, return a value. Also, I have a model and I would like to store the value returned by the method in this model so that I can use this value in another class. Is it possible to do this?
Method:
fun generatePair(): Pair<String?, String?> {
val rand = Random.nextInt(0, 10)
val num1: String? = "x$rand"
val num2: String? = "y$rand"
return Pair(num1, num2)
}
Model:
data class PairData(
val xData: Long,
val yData: String
)
I want to have the generatePair method running continuously and every time it runs, get a new Pair and store it in data class. After that, I want to get the Pair in other class. How is posible to do this? Maybe with a service?
CodePudding user response:
You could save the collection in a singleton arrayList somewhere in your code:
object accessibleVariables{
val pairList = arrayListOf<PairData>()
}
Then you could do something like this:
fun loopMethod(){
// Start a new thread to prevent blocking other code
Thread{
// You could change this to a variable, to stop the loop when you would like
while(true){
accessibleVariables.pairList.add( generatePair() )
}
}.start()
}