0Pricing
Spring Boot 4 Microservices & REST APIs · Aula

Fundamentos de Mono e Flux

Entenda os publicadores reativos.

Fundamentos de Mono e Flux é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What is Reactive Programming

Reactive programming is about building non-blocking, asynchronous applications that handle streams of data.

Instead of returning a value directly, a reactive method returns a publisher that emits data over time. The caller subscribes to receive it.

  • Threads are not blocked waiting for I/O
  • Great for high-concurrency, low-latency services

Project Reactor

Spring WebFlux is built on Project Reactor, which provides two core publisher types:

  • Mono<T> — emits 0 or 1 item
  • Flux<T> — emits 0 to N items

Both implement the Reactive Streams Publisher interface.

Creating a Mono

A Mono represents a single (or empty) async result. Use Mono.just() for a known value and Mono.empty() for none.

Mono<String> mono = Mono.just("Hello");
Mono<String> empty = Mono.empty();
mono.subscribe(value -> System.out.println(value));

Creating a Flux

A Flux emits many items. Build one from values, an iterable, or a range.

Flux<String> flux = Flux.just("a", "b", "c");
Flux<Integer> range = Flux.range(1, 5);
flux.subscribe(item -> System.out.println(item));

Nothing Happens Until Subscribe

Publishers are lazy. The pipeline does nothing until something subscribes.

Calling map() or filter() only describes work. The data flows only when subscribe() is invoked.

Flux<Integer> flux = Flux.range(1, 3)
    .map(i -> i * 10);
// no output yet
flux.subscribe(System.out::println); // now it runs

Transforming with map

map applies a synchronous function to each emitted item, transforming it one-to-one.

Flux<String> names = Flux.just("alice", "bob")
    .map(name -> name.toUpperCase());
names.subscribe(System.out::println);

Filtering Items

filter keeps only items that match a predicate.

Flux<Integer> evens = Flux.range(1, 10)
    .filter(n -> n % 2 == 0);
evens.subscribe(System.out::println);

Mono from a Supplier

Use Mono.fromSupplier() to defer execution of a value-producing function until subscription time.

Mono<Long> now = Mono.fromSupplier(() -> System.currentTimeMillis());
now.subscribe(t -> System.out.println("Time: " + t));

Handling Errors

Reactive pipelines signal errors as a terminal event. Use onErrorReturn to supply a fallback value.

Mono<Integer> result = Mono.just("abc")
    .map(Integer::parseInt)
    .onErrorReturn(-1);
result.subscribe(System.out::println); // -1

Subscribe Callbacks

The full subscribe form accepts three callbacks: onNext, onError, and onComplete.

Flux.just(1, 2, 3)
    .subscribe(
        item -> System.out.println("Next: " + item),
        error -> System.err.println("Error: " + error),
        () -> System.out.println("Done")
    );

Blocking for Tests

In tests or simple mains you can convert reactive types to blocking ones with block() or blockFirst().

Avoid block() in production reactive code — it defeats the non-blocking model.

String value = Mono.just("Hi").block();
Integer first = Flux.range(1, 5).blockFirst();

Quick Check

Test your understanding of Mono and Flux.

Recap

You learned the foundations of reactive programming with Project Reactor:

  • Mono emits 0 or 1 item; Flux emits 0 to N
  • Publishers are lazy — nothing runs until subscribe()
  • map and filter describe transformations
  • onErrorReturn provides fallbacks

Perguntas Frequentes

A aula “Fundamentos de Mono e Flux” é grátis?

Sim — o texto completo de “Fundamentos de Mono e Flux” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “Fundamentos de Mono e Flux”?

Entenda os publicadores reativos. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Fundamentos de Mono e Flux”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Fundamentos de Mono e Flux
  2. Controladores reativos
  3. WebClient para chamadas reativas
  4. Contrapressão e operadores
← Voltar para Spring Boot 4 Microservices & REST APIs