Sobes.tech
Junior — Middle

Can you explain the principle of event-driven approach and how it is used in programming?

sobes.tech AI

Answer from AI

An event-driven approach assumes that a program reacts to certain events — changes in state, user actions, messages, etc. Instead of executing code sequentially, the logic is built around handling these events.

In programming, this is implemented through event generation (emit) and subscription to them (subscribe/listen). When an event occurs, the corresponding handlers are called.

In Go, this approach is often implemented using channels and goroutines. For example, one goroutine can send events to a channel, while another listens to this channel and reacts to events.

Example:

package main

import (
    "fmt"
    "time"
)

func eventProducer(events chan<- string) {
    for i := 1; i <= 5; i++ {
        events <- fmt.Sprintf("Event %d", i)
        time.Sleep(time.Second)
    }
    close(events)
}

func eventConsumer(events <-chan string) {
    for event := range events {
        fmt.Println("Processing", event)
    }
}

func main() {
    events := make(chan string)
    go eventProducer(events)
    eventConsumer(events)
}

This approach increases the flexibility and scalability of applications, especially in systems with asynchronous data processing.