How to return some value from `for_each` stream method?

Hello, I am trying to build functional state management, where, input stream will accept the data and then return the updated state.

But, it seems for_each can’t return any value.

Does anyone have any idea, how to do that?

To transform each value yielded by a stream, you can use map(), and_then, then, or some of the other combinators that receive an item as an argument and allow you to return a new item. Note that some of these combinators return an IntoFuture and some return just a new value directly (like map()).

I can understand. I thought, if we could return some value at the end of the future then I would be able to manage state.

Can we run something other than futures on executors?

Honestly, state management is kinda becoming the really confusing thing with async programming, while that is supposed to be the easiest thing.

If possible, can you suggest some way i can do state management, by message passing, without using mutexes and all.

I think one way to do is, create a channel and then send messages to self, that way i can update the state without have to worry about mutexes and all right ? what do you think ?

Take a look at fold() - it takes an initial value, and allows you to accumulate into it with each yielded item.

The canonical way is probably to use channels, either the mpsc ones and/or the ones from the futures crate.

1 Like

What do you mean by messages to “self”? What’s the self here? But yeah, channels are often used to communicate messages between threads.

so, the whole point i am discussing in here is, i want to build server and when client connects, i want to store client info in client_id => Sink mapping.

Now, if i use just struct then i will have to go throught mutexes. i don’t want that.

So, i want to build something like actor model, where, every async future behave like actor, so, all the tcp clients, will listen to tcp packets as well as some other mpsc channel.

The same, way, server will also listen to tcp listener and there will be a dedicated mpsc channel where server will listen to messages. so, here, when new client connects, i can send message to server as self that, hey, add this client and this Sink mapping to state.

So, this way, i don’t think i will ever have to use mutexes, am i right ?

I’m a bit short on time right this second but take a look at the actix crate - it’s an actor framework that you might be able to build on if you want actor style design.

awesome, thanks. you have been great help. can i get you email, in case if i need to ask you bit more in detail ?