简体   繁体   English

如何在不阻塞的情况下从 Flux 获取列表?

[英]How to get a List from Flux without blocking?

I have a repository that returns a flux and wanted to set the result to another object which is expecting a list.我有一个返回通量的存储库,并希望将结果设置为另一个需要列表的对象。 Is there any other way to get the results as a list without blocking?有没有其他方法可以将结果作为列表而不阻塞?

The block is working but it is taking long time.该块正在工作,但需要很长时间。

public class FluxToListTest {

    @Autowired PostRepository postRepository;

    public void setUserPosts(User user) {
      user.setPostList(postRepository.findAllByOrderId(user.getId()).collectList().block());
  }
}


interface PostRepository {

    Flux<Post> findAllByOrderId(final UUID userId);
}


@Data
class User {
  UUID id;
  List<Post> postList;
}


class Post {
    UUID id;
    String content;
}

In short - NO .总之 - You don't need to extract List from Flux .您不需要从Flux提取List If you've started use Reactor Streams - stay with it.如果您已经开始使用 Reactor Streams - 继续使用它。

Try this code:试试这个代码:

public void setUserPosts(User user) {
    postRepository.findAllByOrderId(user.getId())
        .collectList()
        .doOnNext(user::setPostList)// (1)
        .subscribe();               // (2) 
}  
  1. if you set operation is blocking please use publishOn / subscribeOn to avoid blocking for the all stream.如果您设置操作阻塞,请使用publishOn / subscribeOn以避免阻塞所有流。
  2. it starts your stream performing它开始你的流表演

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM