scala - How to traverse a Set[Future[Option[User]]] and mutate a map -


i have mutable map contains users:

val usermap = mutable.map.empty[int, user] // int user.id 

now need load new users, , add them map. have following api methods:

def getnewusers(): seq[int] def getuser(userid: int): future[option[user]] 

so first users need load:

val newuserids: set[int] = api.getnewusers 

i need load each user, not sure how getuser returns future[option[user]].

i tried this:

api.getnewusers().map( getuser(_) ) 

but returns set[future[option[user]]]

i'm not sure how use set[future[option[user]]] update usermap now.

you'll have wait of futures finish. can use future.sequence transform set[future[_]] future[set], can wait them finish:

val s: set[scala.concurrent.future[some[user]]] = set(future(some(user(1))), future(some(user(2))))  val f: future[set[some[user]]] = future.sequence(s)  f.map(users => users.foreach(u => /* code here */)) 

however, using mutable map may dangerous because it's possible open race conditions. futures executed in different threads, , if altering mutable object's state in different threads, bad things happen.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -