Hello, just wondering is there any way i can lock ...
# android
l
Hello, just wondering is there any way i can lock a property in kotlin when modifying it so i dont get concurrent modification?
use the lazy delegate and specify the mode
l
@rkeazor thanks, but how would this work for example when i need to add an entry to my list from several threads?
d
@Loránd You could use an
actor
or
Mutex
from coroutines, coroutines are made for easy concurrency.
l
@dave08 I ended up using
synchronized(lock:) {}
no idea if that will do the trick but at least it seems to work
d
@Loránd You need the lock at every place you modify the list, if you're using concurrency alot, it might be worth taking a look at the coroutines guide on github kotlinx.coroutines repository... it'll make your code SO much cleaner...
l
@dave08 I will do, i was just thinking. A coroutine will run on a separate thread if i am not mistaken, when i combine that with a library like retrofit wouldnt that just create 2 background threads? or am i missing something?
d
@lofe Jake Wharton made an adapter lib to use retrofit with coroutines, I think that'll just suspend w/o blocking a thread, until response is received. Coroutines use a thread pool, but while waiting for a result, it suspends the execution of the code in it, and lets other coroutines run on the pool, until it gets the result and 'wakes up' the suspended one.
l
Thanks 🙂