Async state handling

Resource observer

Annotated the methods to run on each state with the following annotations:

  • @OnSucess(id="id")

  • @OnError(id="id")

  • @OnLoading(id="id")

Each annotation takes an identifies to identify the operation running. We can have multiple resource observer annotated fields.

Lets see an example for fetching a list of users

UsersFragment
@BindViewModel
lateinit var thirdVm: MyViewModel

@ResourceObserver(id = "users")
lateinit var usersObserver: StateObserver<User>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    vm.liveData.observe(this, usersObserver)
    vm.getUsers()
}

@OnSuccess(id = "users")
fun renderUsers(user: User) {
    Log.d(TAG, "Render user: $user")
}

@OnError(id = "users")
fun renderError(t: Throwable) {
    Log.d(TAG, "Show error")
}

@OnLoading(id = "users")
fun showLoading() {
    Log.d(TAG, "Show loading")
}

Let's walk trough it:

  • Line 5 - Bind the view model Observer using @ResourceObserverannotation.

  • Line 11 - Use the observer in view model

  • Line 15 - Method that runs when the operation completes successfully. The method receives the payload in parameters.

  • Line 21 - On error annotated method that runs when the operation completes with an error. The method receives a throwable representing the error.

  • Line 26 - On loading annotated method that runs while the operation is executing.

Last updated