DEV Community

HarmonyOS
HarmonyOS

Posted on

MVVM Architecture with ObservedV2 and ComponentV2 in HarmonyOS Next

Read the original article:MVVM Architecture with ObservedV2 and ComponentV2 in HarmonyOS Next

Introduction

HarmonyOS Next introduces a modern way to build reactive and maintainable applications for smart devices. With the combination of MVVM architecture, ObservedV2 state management, and ComponentV2 UI components, developers can easily create scalable, testable, and user-friendly apps. In this article, we will explore how to use these features together for efficient development.

Description

MVVM stands for Model-View-ViewModel. It is a design pattern that separates the data (Model), UI (View), and the logic that connects them (ViewModel). This structure makes your codebase more organized, testable, and reusable.

In HarmonyOS Next, you can create a reactive ViewModel by using the @ObservedV2 decorator. Properties you want to track for UI updates are marked with @Trace.

Model

First, define a data model:

export interface GolfClub {
  name: string;
  holes: number;
}
Enter fullscreen mode Exit fullscreen mode

ViewModel

Now, create a ViewModel with @ObservedV2 and reactive properties using @Trace:

@ObservedV2

@ObservedV2

export class HomeViewModel {

  @Trace public clubs: GolfClub[] = [];
  @Trace public isLoading: boolean = false;

  loadClubs() {
    this.isLoading = true;
    // Imagine an API call here
    setTimeout(() => {
      this.clubs = [
        { name: 'Green Hills', holes: 18 },
        { name: 'Lakeside', holes: 9 },
      ];
      this.isLoading = false;
    }, 1500);}}
Enter fullscreen mode Exit fullscreen mode

View

You can build the user interface by defining a component using @ComponentV2.
The UI automatically reacts to changes in your ViewModel thanks to the observability

@ComponentV2

export struct HomeView {
  @Local vm: HomeViewModel = new HomeViewModel();

  aboutToAppear() {
    this.vm.loadClubs();
  }

  build() {
    Column({ space: 18 }) {
      if (this.vm.isLoading) {
        Text("Loading clubs...")
      } else {
        ForEach(this.vm.clubs, (club: GolfClub) => {
          Row() {
            Text(club.name)
          }
        })
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

· When isLoading is true, a loading message is shown.

· When clubs are loaded, they are listed in the UI.

· UI updates automatically when data changes in the ViewModel.

Conclusion

With HarmonyOS Next, combining MVVM architecture, ObservedV2, and ComponentV2 lets you write clean, reactive, and maintainable code.
· Use @ObservedV2 and @Trace for state management.

· Use @ComponentV2 for modular UI components.

· Your UI and business logic stay clearly separated and easy to manage.

Try this approach for your next HarmonyOS Next project for a better development experience!

Written by Ahmet Furkan Sevim

Top comments (0)