如何访问存储库 [MVVM] 中的上下文

How to access context in repository [MVVM]

我正在开发一个使用 MVVM 架构的 Android 应用程序。我的问题是我的存储库(负责从网络获取 JSON)需要访问上下文。

我在 Whosebug 上阅读了一些建议。到目前为止,我收集到的最合理的选择如下:

现在我有一个 ViewModel 和一个 Repo

RoomFragmentViewModel.java:

public class MyViewModel extends ViewModel {
    private MutableLiveData<List<JSONObject>> rooms;
    private Repository repository;

    public void init(){
        if(rooms != null){
            return;
        }
        repository = repository.getInstance();
        rooms = repository.getRooms();
    }

Repository.java:

public class Repository {

    private static Repository instance;
    private ArrayList<JSONObject> actualRooms = new ArrayList<>();


    public static Repository getInstance() {
        if (instance == null) {
            instance = new Repository();
        }
        return instance;
    }

   
    public MutableLiveData<List<JSONObject>> getRooms() {
        ...
    }

    private void setRooms() {
        ...
        // Here I am fetching data from my server, but in order to to do so I require a context

        String url = "http://10.0.0.5:8000/api";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.GET, null, new Response.Listener<JSONObject>() {...

        // Context needs to be provided right here:
        MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

    }
}

由于 Internet 上的说法相互矛盾,我不确定应该如何解决这个问题。如果你的答案使用了匕首,你能不能用代码提供解释,因为我对匕首是全新的。提前谢谢你。

我最终通过匕首注入了上下文。但是,从我的角度来看,使 ViewModelAndroidViewModel 扩展也是一个有效的选择,而且绝对更容易。如果我正在开发一个简单的小型应用程序,我可能会建议只从 AndroidViewModel 扩展,以避免 dagger 中不必要的样板代码。

为了实现我自己的解决方案,我关注了 codingwithmith 的 dagger 系列。 所以他的频道可能对未来的读者有用: https://www.youtube.com/channel/UCoNZZLhPuuRteu02rh7bzsw/featured

使用 Android 刀柄

//Dagger - Hilt
def hilt_version = "2.31.2-alpha"
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

def hilt_viewmodel_version = "1.0.0-alpha03"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_viewmodel_version"
kapt "androidx.hilt:hilt-compiler:$hilt_viewmodel_version"

.

@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Singleton
    @Provides
    fun provideContext(application: Application): Context = application.applicationContext
}

然后通过构造函数传递

class MyRepository @Inject constructor(private val context: Context) {
...
}