使用两种方式的数据绑定字段将数据从存储库传输到片段的最佳方法?

时间:2019-10-21 14:03:05

标签: android mvvm android-livedata

我有一个片段,它通过user id从另一个片段接收safe args。另外,我还有一个存储库,具有通过LiveData<User>返回id的功能。该片段包含multiple text fields,该viewModel通过two-way data binding连接到LiveData transformations

从存储库向片段字段传输数据的最佳方法是什么?

我知道两种方法,但我认为这不是最好的方法(两者都使用val fName = MutableLiveData<String>() // Two-way data-binding, exposing MutableLiveData ... private val userId = MutableLiveData<String>() val userData: LiveData<User> = Transformations.switchMap(userId) { id -> userRepo.getUserById(id) } /** * Called after subscription to the userData */ fun loadData(id: String) { userId.value = id } )。

1)

AddEditUserViewModel

viewModel.userData.observe(this, Observer {
    viewModel.fName.value = it?.fName
    ...
})
args.userId?.let { viewModel.loadData(it) }

AddEditUserFragment

blank observer

2)

第二种方法有fun loadData(id : String) : LiveData<User> { val liveData = MediatorLiveData<User>() liveData.addSource(userRepo.getUserById(id)) { it?.let { fName.value = it.fName ... } } return liveData } ,这不好。

AddEditUserViewModel

args.userId?.let { viewModel.loadData(it).observe(this, Observer {}) }

AddEditUserFragment

 export class ElectronService {
      public ipc: IpcRenderer

      constructor(private snackBar: SnackbarService) {
        if ((<any>window).require) {
          try {
            this.ipc = (<any>window).require('electron').ipcRenderer
          } catch (error) {
            throw error
          }
        } else {
          console.warn('not for this platform')
        }
      }
      async getFiles(plaques: string[]) {
        new Promise<string[]>((resolve, reject) => {
          this.ipc.once("getFilesResponse", (event, arg) => {
            resolve(arg);
          });
          this.ipc.send("getFiles", plaques);
        });

      }
    }

0 个答案:

没有答案