Che*_*eng 5 android android-architecture-components
最近,我坚持使用以下代码.
public class NoteViewModel extends ViewModel {
private final MutableLiveData<List<Note>> notesLiveData = new MutableLiveData<>();
public NoteViewModel() {
LiveData<List<Note>> notesLiveDataFromRepository = NoteRepository.INSTANCE.getNotes();
// How can I "assign" LiveData from Room, to MutableLiveData?
}
}
Run Code Online (Sandbox Code Playgroud)
我在想,我怎么能"分配" LiveData的Room,到MutableLiveData?
使用Transformation.map和Transformation.switchMap不使用,因为两者都返回LiveData,而不是MutableLiveData.
其中一个可能的解决方案是,而不是
@Dao
public abstract class NoteDao {
@Transaction
@Query("SELECT * FROM plain_note")
public abstract LiveData<List<Note>> getNotes();
Run Code Online (Sandbox Code Playgroud)
我会用的
@Dao
public abstract class NoteDao {
@Transaction
@Query("SELECT * FROM plain_note")
public abstract List<Note> getNotes();
Run Code Online (Sandbox Code Playgroud)
然后,在我ViewModel,我会写
public class NoteViewModel extends ViewModel {
private final MutableLiveData<List<Note>> notesLiveData = new MutableLiveData<>();
public NoteViewModel() {
new Thread(() -> {
List<Note> notesLiveDataFromRepository = NoteRepository.INSTANCE.getNotes();
notesLiveData.postValue(notesLiveDataFromRepository);
}).start();
}
}
Run Code Online (Sandbox Code Playgroud)
我真的不喜欢这种方法,因为我被迫明确处理线程化问题.
有没有更好的方法,以避免明确处理线程?
诀窍是不在视图模型中进行任何实际的提取.
从网络或数据库获取数据应该在存储库中完成.在这方面,ViewModel应该是不可知的.
在ViewModel中,使用LiveData类,而不是MutableLiveData.除非你真的找到它的用例.
// In your constructor, no extra thread
notesLiveData = notesLiveDataFromRepository.getAllNotes();
Run Code Online (Sandbox Code Playgroud)
然后在您的存储库中,您可以使用getAllNotes()方法中的逻辑来确定这些注释的来源.在存储库中,您拥有MutableLiveData.然后,您可以从获取数据的线程postValue.这对于房间来说不是必需的,这是为你处理的.
因此,在您的存储库中,您将返回另一个直接从DAO方法支持的LiveData.
在这种情况下,你需要坚持下去public abstract LiveData<List<Note>> getNotes();.
public class MyActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up your view model
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
// Observe the view model
viewModel.getMyLiveData().observe(this, s -> {
// You work with the data provided through the view model here.
// You should only really be delivering UI updates at this point. Updating
// a RecyclerView for example.
Log.v("LIVEDATA", "The livedata changed: "+s);
});
// This will start the off-the-UI-thread work that we want to perform.
MyRepository.getInstance().doSomeStuff();
}
}
Run Code Online (Sandbox Code Playgroud)
public class MyViewModel extends AndroidViewModel {
@NonNull
private MyRepository repo = MyRepository.getInstance();
@NonNull
private LiveData<String> myLiveData;
public MyViewModel(@NonNull Application application) {
super(application);
// The local live data needs to reference the repository live data
myLiveData = repo.getMyLiveData();
}
@NonNull
public LiveData<String> getMyLiveData() {
return myLiveData;
}
}
Run Code Online (Sandbox Code Playgroud)
public class MyRepository {
private static MyRepository instance;
// Note the use of MutableLiveData, this allows changes to be made
@NonNull
private MutableLiveData<String> myLiveData = new MutableLiveData<>();
public static MyRepository getInstance() {
if(instance == null) {
synchronized (MyRepository.class) {
if(instance == null) {
instance = new MyRepository();
}
}
}
return instance;
}
// The getter upcasts to LiveData, this ensures that only the repository can cause a change
@NonNull
public LiveData<String> getMyLiveData() {
return myLiveData;
}
// This method runs some work for 3 seconds. It then posts a status update to the live data.
// This would effectively be the "doInBackground" method from AsyncTask.
public void doSomeStuff() {
new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {
}
myLiveData.postValue("Updated time: "+System.currentTimeMillis());
}).start();
}
}
Run Code Online (Sandbox Code Playgroud)
很简单。
class MainViewModel: ViewModel() {
@Inject lateinit var currencyRepository: CurrencyRepository
val notifyCurrencyList = MediatorLiveData<List<Currency?>>()
init {
CurrencyApplication.component.inject(this)
}
fun loadCurrencyList() {
notifyCurrencyList.addSource(currencyRepository.loadLatestRates()) {
notifyCurrencyList.value = it
}
}
}
Run Code Online (Sandbox Code Playgroud)