我有一个片段,它通过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
}
)。
AddEditUserViewModel
viewModel.userData.observe(this, Observer {
viewModel.fName.value = it?.fName
...
})
args.userId?.let { viewModel.loadData(it) }
AddEditUserFragment
blank observer
第二种方法有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);
});
}
}