https://kotlinlang.org logo
Title
s

Shawn Witte

10/20/2020, 9:10 PM
I have a
suspend
function that launches several operations (syncing individual pieces of local data) and I don't want this function to be run more than once simultaneously (if we try to POST the same data twice, then we get two new entries on the server side). What is the preferred practice for preventing a second simultaneous execution of this function? I have an idea, but I wanted the community opinion since there was some concern about my answer in a code review.
l

louiscad

10/20/2020, 9:12 PM
Shared
Mutex
instance +
withLock { }
usage.
s

Shawn Witte

10/20/2020, 9:34 PM
That was what I went with. Although, I'm not sure what you mean by "shared"
Mutex
? Can/should I put it in the
companion object
so the function can only run once among all instances of the class (as opposed to preventing multiple calls to one instance)? Seems like that should still be safe as long as it remains a
private
value.
l

louiscad

10/21/2020, 4:34 AM
Yes, one private instance in a companion object is what I called "shared"
s

Shawn Witte

10/21/2020, 6:32 AM
Thanks. For some reason I didn't think of that at first and I was considering trying to make the class a singleton to make sure there was only one mutex 🤦‍♂️.