最近,我坚持使用以下代码。
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?
}
}
我想知道,我如何从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();
我会用
@Dao
public abstract class NoteDao {
@Transaction
@Query("SELECT * FROM plain_note")
public abstract List<Note> getNotes();
然后,在我的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();
}
}
我真的不喜欢这种方法,因为我被迫明确处理线程化问题。
有没有更好的方法,以避免明确处理线程?
答案 0 :(得分:8)
诀窍是不在视图模型中进行任何实际的提取。
从网络或数据库获取数据应该在存储库中完成。在这方面,ViewModel应该是不可知的。
在ViewModel中,使用LiveData类,而不是MutableLiveData。除非你真的找到了一个用例。
// In your constructor, no extra thread
notesLiveData = notesLiveDataFromRepository.getAllNotes();
然后在您的存储库中,您可以使用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();
}
}
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;
}
}
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();
}
}
答案 1 :(得分:0)
非常简单。
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
}
}
}