代码之家  ›  专栏  ›  技术社区  ›  PrashanD

获取活动或片段外部viewmodel实例的正确方法

  •  6
  • PrashanD  · 技术社区  · 6 年前

    我正在构建一个位置应用程序,在主活动中显示来自房间数据库的背景位置。我可以通过调用

    locationViewModel = ViewModelProviders.of(this).get(LocationViewModel.class);
    locationViewModel.getLocations().observe(this, this);
    

    当我通过广播接收器接收位置更新时,应将定期的背景位置保存到房间数据库中。应该打电话救他们 locationViewModel.getLocations().setValue()

    public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver {
    
        static final String ACTION_PROCESS_UPDATES =
                "com.google.android.gms.location.sample.backgroundlocationupdates.action" +
                        ".PROCESS_UPDATES";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_PROCESS_UPDATES.equals(action)) {
                    LocationResult result = LocationResult.extractResult(intent);
                    if (result != null) {
                        List<Location> locations = result.getLocations();
                        List<SavedLocation> locationsToSave = covertToSavedLocations(locations)
                        //Need an instance of LocationViewModel to call locationViewModel.getLocations().setValue(locationsToSave)
                    }
                }
            }
        }
    }
    

    问题是,我应该如何获取像这个广播接收器这样的非活动类中的locationViewModel实例?打电话对吗 locationViewModel = ViewModelProviders.of(context).get(LocationViewModel.class) 其中context是我从中接收的context onReceive (Context context, Intent intent) 广播接收器的?

    获取viewmodel后,是否需要使用 LiveData.observeForever LiveData.removeObserver 因为广播接收器不是生命周期所有者?

    2 回复  |  直到 6 年前
        1
  •  5
  •   Sagar    6 年前

    问题是如何在 像这样的非活动类广播接收器?

    你不应该那样做。它糟糕的设计实践。

    调用LocationViewModel是否正确= (上下文).GET(LoopVIEW模型.class)在哪里 context是我从onreceive(context context, 意图)的广播接收器?

    不,没用的

    您可以实现以下预期结果:

    将房间数据库操作与 ViewModel 在一个单独的单子课上。把它用在 视图模型 以及其他需要的地方。当接收到广播时,通过这个单级类将数据写入DB,而不是 视图模型 是的。

    如果你在观察 LiveData 在你的片段中,它也会更新你的视图。

        2
  •  0
  •   ericn    6 年前

    传递viewmodel实例是反模式的。
    在你的情况下,通过 locationViewModel.getLocations() 而是在周围。
    我不太熟悉体系结构组件,但是在标准的android数据绑定中,可以通过 Observable* 用于设置和获取其值的实例